How can I get the current time (now) in UTC?
Use the following:
from datetime import timezone
utc_datetime = local_datetime.astimezone().astimezone(timezone.utc).replace(tzinfo=None)
Given a naive datetime object assumed to have a local datetime, you can use the following sequence of method calls to convert it to a naive UTC datetime representing the same UTC time (tested with Python 3.6.3).
- astimezone() to add the local timezone so it's no longer naive.
- astimezone(timezone.utc) to convert it from local to UTC.
- replace(tzinfo=None) to remove the timezone so it's naive again, but now UTC
Example:
>>> local_datetime = datetime.now()
>>> local_datetime
datetime.datetime(2019, 12, 14, 10, 30, 37, 91818)
>>> local_datetime.astimezone()
datetime.datetime(2019, 12, 14, 10, 30, 37, 91818, tzinfo=datetime.timezone(datetime.timedelta(-1, 68400), 'Eastern Standard Time'))
>>> local_datetime.astimezone().astimezone(timezone.utc)
datetime.datetime(2019, 12, 14, 15, 30, 37, 91818, tzinfo=datetime.timezone.utc)
>>> local_datetime.astimezone().astimezone(timezone.utc).replace(tzinfo=None)
datetime.datetime(2019, 12, 14, 15, 30, 37, 91818)
Note: The first astimezone() is not really needed because of this note in the Python docs:
Changed in version 3.6: The astimezone() method can now be called on naive instances that are presumed to represent system local time.
For those who ended up here looking for a way to convert a datetime object to UTC seconds since UNIX epoch:
import time
import datetime
t = datetime.datetime.now()
utc_seconds = time.mktime(t.timetuple())
First you need to make sure the datetime is a timezone-aware object by setting its tzinfo
member:
http://docs.python.org/library/datetime.html#datetime.tzinfo
You can then use the .astimezone()
function to convert it:
http://docs.python.org/library/datetime.html#datetime.datetime.astimezone
Run this to obtain a naive datetime in UTC (and to add five minutes to it):
>>> from datetime import datetime, timedelta
>>> datetime.utcnow()
datetime.datetime(2021, 1, 26, 15, 41, 52, 441598)
>>> datetime.utcnow() + timedelta(minutes=5)
datetime.datetime(2021, 1, 26, 15, 46, 52, 441598)
If you would prefer a timezone-aware datetime object, run this in Python 3.2 or higher:
>>> from datetime import datetime, timezone
>>> datetime.now(timezone.utc)
datetime.datetime(2021, 1, 26, 15, 43, 54, 379421, tzinfo=datetime.timezone.utc)