Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an UTC date string in Python? [duplicate]

I am trying to get utc date string as "YYYYMMDD"

For now I do the following,

nowTime =  time.gmtime(); nowDate = date(nowTime.tm_year, nowTime.tm_mon, nowTime.tm_mday) print nowDate.strftime('%Y%m%d') 

I used to do:

datetime.date.today().strftime() 

but this gives me date string in local TZ

How can I get an UTC date string?

like image 523
GJain Avatar asked Jul 23 '13 22:07

GJain


People also ask

How do I print the UTC date in Python?

Simply use datetime. datetime. utcnow(). strftime("%a %b %d %H:%M:%S %Z %Y") can solve your problem already.

How do I change the UTC date in Python?

This datetime object will have no timezone associated with it. Therefore assign the UTC timezone to this datetime object using replace(tzinfo=pytz. UTC) function. Convert the timezone of the datetime object to local timezone by calling the astimezone() function on datetime object.

Is Python datetime in UTC?

You can use the datetime module to convert a datetime to a UTC timestamp in Python. If you already have the datetime object in UTC, you can the timestamp() to get a UTC timestamp. This function returns the time since epoch for that datetime object.


1 Answers

from datetime import datetime, timezone datetime.now(timezone.utc).strftime("%Y%m%d") 

Or as Davidism pointed out, this would also work:

from datetime import datetime datetime.utcnow().strftime("%Y%m%d") 

I prefer the first approach, as it gets you in the habit of using timezone aware datetimes - but as J.F. Sebastian pointed out - it requires Python 3.2+. The second approach will work in both 2.7 and 3.2 branches.

like image 154
Matt Johnson-Pint Avatar answered Sep 27 '22 20:09

Matt Johnson-Pint