简体   繁体   中英

How to format the current date and time to include which timezone?

I would like to get the current date and time in the following format:

2017-12-27T15:20:11+05:30

How do I do it ?

If I do:

now = datetime.datetime.now()
print now.isoformat()

Then it comes out like this:

2014-09-26T16:34:40.278298

You need a timezone aware datetime:

>>> from datetime import datetime, timezone
>>> datetime.now(timezone.utc).isoformat()
'2017-12-28T05:22:22.759548+00:00'

If you don't want sub-second accuracy:

>>> datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%S%z')
'2017-12-28T05:23:11+0000'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM