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 hopefull
In python3:
pip install python-dateutil
from dateutil.parser import tz
mydt.astimezone(tz.gettz('UTC')).replace(tzinfo=None)
import time
import datetime
def Local2UTC(LocalTime):
EpochSecond = time.mktime(LocalTime.timetuple())
utcTime = datetime.datetime.utcfromtimestamp(EpochSecond)
return utcTime
>>> LocalTime = datetime.datetime.now()
>>> UTCTime = Local2UTC(LocalTime)
>>> LocalTime.ctime()
'Thu Feb 3 22:33:46 2011'
>>> UTCTime.ctime()
'Fri Feb 4 05:33:46 2011'
def local_to_utc(t):
secs = time.mktime(t)
return time.gmtime(secs)
def utc_to_local(t):
secs = calendar.timegm(t)
return time.localtime(secs)
Source: http://feihonghsu.blogspot.com/2008/02/converting-from-local-time-to-utc.html
Example usage from bd808: If your source is a datetime.datetime
object t
, call as:
local_to_utc(t.timetuple())
This thread seems to be missing an option available since Python 3.6: datetime.astimezone(tz=None)
can be used to get an aware datetime object representing local time (docs). This can then easily be converted to UTC.
from datetime import datetime, timezone
s = "2008-09-17 14:02:00"
# to datetime object:
dt = datetime.fromisoformat(s) # Python 3.7
# I'm on time zone Europe/Berlin; CEST/UTC+2 during summer 2008
dt = dt.astimezone()
print(dt)
# 2008-09-17 14:02:00+02:00
# ...and to UTC:
dtutc = dt.astimezone(timezone.utc)
print(dtutc)
# 2008-09-17 12:02:00+00:00
There is one caveat though, see astimezone(None) gives aware datetime, unaware of DST.
How about -
time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(seconds))
if seconds is None
then it converts the local time to UTC time else converts the passed in time to UTC.
You can do it with:
>>> from time import strftime, gmtime, localtime
>>> strftime('%H:%M:%S', gmtime()) #UTC time
>>> strftime('%H:%M:%S', localtime()) # localtime