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.
Using http://crsmithdev.com/arrow/
This library makes life easy :)
In python3:
pip install python-dateutil
You can do it with:
First, parse the string into a naive datetime object. This is an instance of
datetime.datetime
with no attached timezone information. See documentation fordatetime.strptime
for information on parsing the date string.Use the
pytz
module, which comes with a full list of time zones + UTC. Figure out what the local timezone is, construct a timezone object from it, and manipulate and attach it to the naive datetime.Finally, use
datetime.astimezone()
method to convert the datetime to UTC.Source code, using local timezone "America/Los_Angeles", for the string "2001-2-3 10:11:12":
From there, you can use the
strftime()
method to format the UTC datetime as needed:I've had the most success with python-dateutil: