45

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?

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
GJain
  • 5,025
  • 6
  • 48
  • 82

1 Answers1

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

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575