Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 678
Elias Zamaria Avatar asked Jul 25 '10 03:07

Elias Zamaria


People also ask

What is my current TimeZone UTC?

Current time: 15:14:21 UTC. UTC is replaced with Z that is the zero UTC offset. UTC time in ISO-8601 is 15:14:21Z.

How can I get current date in UTC?

SimpleDateFormat f = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss"); f. setTimeZone(TimeZone. getTimeZone("UTC")); System. out.

What is UTC time now in 24 hour format?

05:30:03 P.M.


2 Answers

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) 
like image 90
Senyai Avatar answered Sep 21 '22 15:09

Senyai


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

like image 23
Amber Avatar answered Sep 20 '22 15:09

Amber