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
I have this code in one of my projects:
from datetime import datetime
## datetime.timezone works in newer versions of python
try:
from datetime import timezone
utc_tz = timezone.utc
except:
import pytz
utc_tz = pytz.utc
def _to_utc_date_string(ts):
# type (Union[date,datetime]]) -> str
"""coerce datetimes to UTC (assume localtime if nothing is given)"""
if (isinstance(ts, datetime)):
try:
## in python 3.6 and higher, ts.astimezone() will assume a
## naive timestamp is localtime (and so do we)
ts = ts.astimezone(utc_tz)
except:
## in python 2.7 and 3.5, ts.astimezone() will fail on
## naive timestamps, but we'd like to assume they are
## localtime
import tzlocal
ts = tzlocal.get_localzone().localize(ts).astimezone(utc_tz)
return ts.strftime("%Y%m%dT%H%M%SZ")
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.
Here's a summary of common Python time conversions.
Some methods drop fractions of seconds, and are marked with (s). An explicit formula such as ts = (d - epoch) / unit
can be used instead (thanks jfs).
calendar.timegm(struct_time)
calendar.timegm(stz.localize(dt, is_dst=None).utctimetuple())
calendar.timegm(dt.utctimetuple())
calendar.timegm(dt.utctimetuple())
time.gmtime(t)
stz.localize(dt, is_dst=None).utctimetuple()
dt.utctimetuple()
dt.utctimetuple()
datetime.fromtimestamp(t, None)
datetime.datetime(struct_time[:6], tzinfo=UTC).astimezone(tz).replace(tzinfo=None)
dt.replace(tzinfo=UTC).astimezone(tz).replace(tzinfo=None)
dt.astimezone(tz).replace(tzinfo=None)
datetime.utcfromtimestamp(t)
datetime.datetime(*struct_time[:6])
stz.localize(dt, is_dst=None).astimezone(UTC).replace(tzinfo=None)
dt.astimezone(UTC).replace(tzinfo=None)
datetime.fromtimestamp(t, tz)
datetime.datetime(struct_time[:6], tzinfo=UTC).astimezone(tz)
stz.localize(dt, is_dst=None)
dt.replace(tzinfo=UTC)
Source: taaviburns.ca
If you already have a datetime object my_dt
you can change it to UTC with:
datetime.datetime.utcfromtimestamp(my_dt.timestamp())
Thanks @rofly, the full conversion from string to string is as follows:
time.strftime("%Y-%m-%d %H:%M:%S",
time.gmtime(time.mktime(time.strptime("2008-09-17 14:04:00",
"%Y-%m-%d %H:%M:%S"))))
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 did it like this:
>>> utc_delta = datetime.utcnow()-datetime.now()
>>> utc_time = datetime(2008, 9, 17, 14, 2, 0) + utc_delta
>>> print(utc_time)
2008-09-17 19:01:59.999996
If you want to get fancy, you can turn this into a functor:
class to_utc():
utc_delta = datetime.utcnow() - datetime.now()
def __call__(cls, t):
return t + cls.utc_delta
Result:
>>> utc_converter = to_utc()
>>> print(utc_converter(datetime(2008, 9, 17, 14, 2, 0)))
2008-09-17 19:01:59.999996