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

Question:

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.

Asked By: Elias Zamaria

||

Answers:

You can use the formatdate method in the email.Utils module like follows

>>> from email.Utils import formatdate
>>> print formatdate()
Sun, 25 Jul 2010 04:02:52 -0000

The above is date time in RFC 2822 format. By default it returns UTC time but in-case you need local time you can call formatdate(localtime=True).

For more information do check http://docs.python.org/library/email.mime.html#module-email.util

Answered By: GeekTantra

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

Answered By: Amber

I found a way to take the current time, add a timedelta object to it, convert the result to UTC, and output it in RFC 2822:

time.strftime("%a, %d-%b-%Y %H:%M:%S GMT",
    time.gmtime(time.time() + datetime.timedelta(minutes=5).seconds))

This did not exactly answer my question, but I am putting it here because it may help someone else in my situation.

EDIT: I would like to add that this trick only works if the timedelta is less than one day. If you want something that works with any sort of timedelta value, you can use timedelta.total_seconds() (for Python 2.7 and later), or with 86400*timedelta.days + timedelta.seconds. I haven’t actually tried this so I’m not 100% sure if it will work.

Answered By: Elias Zamaria

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())
Answered By: ishmael

To convert to UTC from a date string:

from time import mktime
from datetime import datetime

mktime(datetime.utctimetuple(datetime.strptime("20110830_1117","%Y%m%d_%H%M")))
Answered By: ElaineN

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)
Answered By: Senyai

solution with fantastic Delorean lib:

>>> import datetime
>>> import delorean
>>> dt = datetime.datetime.now()
>>> dl = delorean.Delorean(dt, timezone='US/Pacific')
>>> dl.shift('UTC')
Delorean(datetime=2015-03-27 03:12:42.674591+00:00, timezone=UTC)

>>> dl.shift('UTC').datetime
datetime.datetime(2015, 3, 27, 3, 12, 42, 674591, tzinfo=<UTC>)

>>> dl.shift('EST').datetime
datetime.datetime(2015, 3, 26, 22, 12, 42, 674591, tzinfo=<StaticTzInfo 'EST'>)

it allows to shift datetime between different timezones easily

Answered By: DmitrySemenov

Here’s a stdlib solution (no 3rd-party modules) that works on both Python 2 and 3.

To get the current UTC time in RFC 2822 format:

>>> from email.utils import formatdate
>>> formatdate(usegmt=True)
'Fri, 27 Mar 2015 08:29:20 GMT'

To get the UTC time 5 minutes into the future:

#!/usr/bin/env python
import time
from email.utils import formatdate

print(formatdate(time.time() + 300, usegmt=True)) # 5 minutes into the future
# -> Fri, 27 Mar 2015 08:34:20 GMT
Answered By: jfs

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.

Answered By: Carlos A. Ibarra
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.