48

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?

0

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

as of 2024-10-02 in Python 3.12.7 the following results in an error: datetime.now(datetime.UTC) AttributeError: type object 'datetime.datetime' has no attribute UTC
@user3785010 - check your code carefully. Nowhere in my examples did I write datetime.UTC.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.