Python Tutorial (33) – Example: Convert a timestamp to a date in a specified format

Time: Column:Python views:269

Convert a Timestamp to a Formatted Time with Timezone Considerations

You can convert a given timestamp to a specified time format using Python. Here are examples demonstrating this process with the year updated to 2024.

Current Time

Example 1: Using time Module

import time

# Get the current timestamp
now = int(time.time())

# Convert timestamp to a formatted date string
timeArray = time.localtime(now)
otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
print(otherStyleTime)

Output:

2024-09-12 18:02:49

This example gets the current timestamp, converts it to a local time structure, and then formats it as a string in the YYYY-MM-DD HH:MM:SS format.

Example 2: Using datetime Module

import datetime

# Get the current datetime
now = datetime.datetime.now()

# Convert datetime to a formatted string
otherStyleTime = now.strftime("%Y-%m-%d %H:%M:%S")
print(otherStyleTime)

Output:

2024-09-12 18:03:48

In this example, the current datetime is formatted directly into a string.

Given Timestamp

Example 3: Using time Module

import time

timeStamp = 1725900000
timeArray = time.localtime(timeStamp)
otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
print(otherStyleTime)

Output:

2024-09-12 23:40:00

Here, a specific timestamp is converted into a formatted string based on local time.

Example 4: Using datetime Module

import datetime

timeStamp = 1725900000
dateArray = datetime.datetime.utcfromtimestamp(timeStamp)
otherStyleTime = dateArray.strftime("%Y-%m-%d %H:%M:%S")
print(otherStyleTime)

Output:

2024-09-12 23:40:00

This example converts a timestamp into a formatted string based on UTC time.

These examples illustrate how to handle timestamps and convert them into readable date and time formats, taking into account both local and UTC timezones.