10

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

2 Answers 2

10

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.

Sign up to request clarification or add additional context in comments.

4 Comments

That worked (I was accidentally running it with python 2).
actually, I spoke too soon. I still have the time delta: d1 = datetime.strptime(timestamp + "+0000", TIME_FORMAT + '%z') 1544063570 vs 1544092370
Surprising, this code works for me, except that I have replaced ts1 = int(d1.strftime("%s")) with ts1 = d1.timestamp() because I had an error. Maybe here is your problem?
yes, now I get the same timestamp. will edit the answer with the full working snippet. thanks again!
4

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)

1 Comment

.replace on tzinfo does not properly handle daylight savings time. Correct answer is: pytz.utc.localize(datetime.strptime(DATE, ...))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.