Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting python UTC timestamp to and from string

Here is a python code snippet that takes the current time (in UTC), converts it to a formatted string and parses the string. I would like to get the same timestamp, but I get a different timestamp because of the time zone I am in.

How can I reconstruct the same time stamp as I started with?

#!/usr/bin/env python3  
import time
from datetime import datetime
TIME_FORMAT='%Y-%m-%d %H:%M:%S'
ts = int(time.time()) # UTC timestamp
timestamp = datetime.utcfromtimestamp(ts).strftime(TIME_FORMAT)
d1 = datetime.strptime(timestamp, TIME_FORMAT)
ts1 = int(d1.strftime("%s"))
print("Time as string : %s" % d1)
print("Source timestamp : %d" % ts)
print("Parsed timestamp : %d" % ts1)

Output:

Time as string : 2018-12-06 00:47:32
Source timestamp : 1544057252
Parsed timestamp : 1544086052
like image 988
Omry Yadan Avatar asked Dec 06 '18 00:12

Omry Yadan


1 Answers

In the string, no timezone is specified, so it is not considered as UTC but as your personal timezone. To solve the problem, you have to specify the string is UTC when parsing, like this:

d1 = datetime.strptime(timestamp + "+0000", TIME_FORMAT + '%z')
ts1 = d1.timestamp()

Full working snippet:

#!/usr/bin/env python3
import time
from datetime import datetime
TIME_FORMAT='%Y-%m-%d %H:%M:%S'
ts = int(time.time()) # UTC timestamp
timestamp = datetime.utcfromtimestamp(ts).strftime(TIME_FORMAT)
d1 = datetime.strptime(timestamp + "+0000", TIME_FORMAT + '%z')
ts1 = d1.timestamp()
print("Time as string : %s" % d1)
print("Source timestamp : %d" % ts)
print("Parsed timestamp : %d" % ts1)

+0000 corresponds to the utc offset.

like image 157
Axel Puig Avatar answered Sep 28 '22 17:09

Axel Puig