Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Convert a Timestamp to a Date in a Specified Format

Python Convert a Timestamp to a Date in a Specified Format

Document Object Reference Manual Python3 Examples

Given a timestamp, convert it to a time in a specified format.

Pay attention to the time zone setting.

Common formatting codes

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

)

print

(

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

"

)

print

(

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

)

print

(

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

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 weekday and full month name

print

(

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"

)

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 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 

Document Object Reference Manual Python3 Examples