How can I get the current time (now) in UTC?

Viewed 90055

I have a python datetime object (representing five minutes from now) which I would like to convert to UTC. I am planning to output it in RFC 2822 format to put in an HTTP header, but I am not sure if that matters for this question. I found some information on this site about converting time objects, and it looks simpler that way, but this time I really want to use datetime objects, because I am using timedeltas to adjust them:

I tried something like this:

from datetime import datetime, timedelta

now = datetime.now()
fiveMinutesLater = datetime.now() + timedelta(minutes=5)
fiveMinutesLaterUtc = ???

Nothing in the time or datetime module looks like it would help me. It seems like I may be able to do it by passing the datetime object through 3 or 4 functions, but I am wondering if there is a simpler way.

I would prefer not to use third-party modules, but I may if it is the only reasonable choice.

9 Answers

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).

  1. astimezone() to add the local timezone so it's no longer naive.
  2. astimezone(timezone.utc) to convert it from local to UTC.
  3. 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.

Related