Python Timstamp Str
# Python3.x Python: Convert Timestamp to Specified Format Date
[ Python3 Examples](#)
Given a timestamp, convert it to a specified format time.
**Note the timezone settings.**
**Common Formatting Codes Explained**
* `%Y` - Four-digit year (2024)
* `%y` - Two-digit year (24)
* `%m` - Month (01-12)
* `%d` - Day (01-31)
* `%H` - Hour 24-hour format (00-23)
* `%I` - Hour 12-hour format (01-12)
* `%M` - Minute (00-59)
* `%S` - Second (00-59)
* `%p` - AM/PM
* `%A` - Full weekday name (Monday)
* `%a` - Abbreviated weekday name (Mon)
* `%B` - Full month name (January)
* `%b` - Abbreviated month name (Jan)
### Current Time
## Example 1
import time# Get current timestamp now = int(time.time())# Convert to other date format, e.g.: "%Y-%m-%d %H:%M:%S"timeArray = time.localtime(now)otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)print(otherStyleTime)
Executing the above code outputs:
2019-05-21 18:02:49
## Example 2
import datetime# Get current time now = datetime.datetime.now()# Convert to specified format otherStyleTime = now.strftime("%Y-%m-%d %H:%M:%S")print(otherStyleTime)
Executing the above code outputs:
2019-05-21 18:03:48
### Specified Timestamp
## Example 3
import time timeStamp = 1557502800 timeArray = time.localtime(timeStamp)otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)print(otherStyleTime)
Executing the above code outputs:
2019-05-10 23:40:00
Output dates in different formats:
## Example 4
import datetime
timestamp =1710000000
dt_object =datetime.datetime.fromtimestamp(timestamp)
# Format 1: YYYY-MM-DD
print(dt_object.strftime("%Y-%m-%d"))# Output: 2024-03-09
# Format 2: MM/DD/YYYY
print(dt_object.strftime("%m/%d/%Y"))# Output: 03/09/2024
# Format 3: With full weekday and month name
print(dt_object.strftime("%A, %B %d, %Y"))# Output: Saturday, March 09, 2024
Complete example (including timezone handling):
## Example 5
from datetime import datetime, timezone
# Millisecond timestamp (like JavaScript's Date.now())
timestamp_ms =1710000000000
# Convert to seconds and to UTC time
timestamp_s = timestamp_ms / 1000
dt_utc =datetime.fromtimestamp(timestamp_s, tz=timezone.utc)
# Format as UTC time string
formatted_utc = dt_utc.strftime("%Y-%m-%d %H:%M:%S UTC")
print(formatted_utc)# Output: 2024-03-09 00:00:00 UTC
# Convert to local time
dt_local =datetime.fromtimestamp(timestamp_s)
formatted_local = dt_local.strftime("%Y-%m-%d %H:%M:%S %Z")
print(formatted_local)# Output depends on your timezone, e.g.: 2024-03-08 16:00:00 PST
The output is:
2024-03-09 16:00:00 UTC 2024-03-10 00:00:00
[![Image 4: Document Object Reference Manual](http://w
YouTip