Python Convert a Timestamp to a Date in a Specified Format
Given a timestamp, convert it to a time in a specified format.
Pay attention to the time zone setting.
Common formatting codes
%Y- Four-digit year (2024)%y- Two-digit year (24)%m- Month (01-12)%d- Day (01-31)%H- Hour in 24-hour format (00-23)%I- Hour in 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 the current timestamp
now
=
int
(
time
.
time
(
)
)
# Convert to another date format, e.g. "%Y-%m-%d %H:%M:%S"
timeArray
=
time
.
localtime
(
now
)
otherStyleTime
=
time
.
strftime
(
"
%Y-%m-%d %H:%M:%S
"
,
timeArray
)
(
otherStyleTime
)
The output of the code above is:
2019-05-21 18:02:49
Example 2
import
datetime
Get the current time
now
=
datetime
.
datetime
.
now
(
)
Convert to the specified format
otherStyleTime
=
now
.
strftime
(
"
%Y-%m-%d %H:%M:%S
"
)
(
otherStyleTime
)
The output of the code above is:
2019-05-21 18:03:48
Specify a timestamp
Example 3
import
time
timeStamp
=
1557502800
timeArray
=
time
.
localtime
(
timeStamp
)
otherStyleTime
=
time
.
strftime
(
"
%Y-%m-%d %H:%M:%S
"
,
timeArray
)
(
otherStyleTime
)
The output of the code above is:
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
(
dt_object.
strftime
(
"%Y-%m-%d"
)
)
Output: 2024-03-09
Format 2: MM/DD/YYYY
(
dt_object.
strftime
(
"%m/%d/%Y"
)
)
Output: 03/09/2024
Format 3: with weekday and full month name
(
dt_object.
strftime
(
"%A, %B %d, %Y"
)
)
Output: Saturday, March 09, 2024
Complete example (including time zone handling):
Example 5
from
datetime
import
datetime
,
timezone
Millisecond-level timestamp (such as 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 a UTC time string
formatted_utc
=
dt_utc.
strftime
(
"%Y-%m-%d %H:%M:%S UTC"
)
(
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"
)
(
formatted_local
)
Output depends on your time zone, for example: 2024-03-08 16:00:00 PST
The output is:
2024-03-09 16:00:00 UTC
2024-03-10 00:00:00
Python3 Examples