How do I convert a datetime string in local time to a string in UTC time?
I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future.
Clarification: For example, if I have 2008-09-17 14:02:00
in my local timezone (+10
), I'd like to generate a string with the equivalent UTC
time: 2008-09-17 04:02:00
.
Also, from http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/, note that in general this isn't possible as with DST and other issues there is no unique conversion from local time to UTC time.
Thanks @rofly, the full conversion from string to string is as follows:
My summary of the
time
/calendar
functions:time.strptime
string --> tuple (no timezone applied, so matches string)
time.mktime
local time tuple --> seconds since epoch (always local time)
time.gmtime
seconds since epoch --> tuple in UTC
and
calendar.timegm
tuple in UTC --> seconds since epoch
time.localtime
seconds since epoch --> tuple in local timezone
I'm having good luck with dateutil (which is widely recommended on SO for other related questions):
(Code was derived from this answer to Convert UTC datetime string to local datetime)
For getting around day-light saving, etc.
None of the above answers particularly helped me. The code below works for GMT.
One more example with pytz, but includes localize(), which saved my day.
Simple
I did it like this:
Fancy Implementation
If you want to get fancy, you can turn this into a functor:
Result:
I found the best answer on another question here. It only uses python built-in libraries and does not require you to input your local timezone (a requirement in my case)
I'm reposting the answer here since this question pops up in google instead of the linked question depending on the search keywords.