Reputation: 53873
I've got a datetime as a string (2016-12-31 23:59
), from which I know it was defined in UTC. I now want to get the timedelta using Python. The machine I'm doing this on will normally be in the CEST time zone (Europe/Amsterdam
), but this might not always be the case and therefore I don't want to hardcode this time zone in the code.
For local timezones this would work great:
date_str = '2016-12-31 23:59'
print datetime.now() - datetime.strptime(date_str, '%Y-%m-%d %H:%M')
this obviously isn't correct though, but changing it to use utcnow()
is also not correct:
print datetime.utcnow() - datetime.strptime(date_str, '%Y-%m-%d %H:%M')
This doesn't work correctly because now the datetime resulting from strptime is in the timezone of the machine this code is running on, while the utcnow() is in UTC.
I found this SO answer, but that assumes you know the timezone of the machine the code is running on, which I don't.
Is there a way that I can add the UTC timezone to the datetime
object which I get from datetime.strptime()
so that I can compare it with utcnow()
? All tips are welcome
Upvotes: 3
Views: 4901
Reputation: 48962
Your code is actually fine. Your mistake is in this assumption: "the datetime resulting from strptime
is in the timezone of the machine this code is running on."
datetime.strptime(date_str, '%Y-%m-%d %H:%M')
will produce a naive datetime representing a time that you said was in UTC.
datetime.utcnow()
will produce a naive datetime representing the current time in UTC.
So the difference will be accurate.
Upvotes: 3