Reputation: 33646
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
Upvotes: 10
Views: 18395
Reputation: 41
From string to timestamp without timezone
from datetime import datetime, timezone
DATE = "2021-05-21 12:00"
ts = datetime.strptime(DATE, "%Y-%m-%d %H:%M").replace(tzinfo=timezone.utc).timestamp()
print(ts)
Upvotes: 4
Reputation: 1334
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.
Upvotes: 10