Search code examples
pythondatetimedatetime-format

How to get current isoformat datetime string including the default timezone?


I need to produce a time string that matches the iso format yyyy-mm-ddThh:mm:ss.ssssss-ZO:NE. The now() and utcnow() class methods almost do what I want.

>>> import datetime
>>> #time adjusted for current timezone
>>> datetime.datetime.now().isoformat()
'2010-08-03T03:00:00.000000'
>>> #unadjusted UTC time
>>> datetime.datetime.utcnow().isoformat()
'2010-08-03T10:00:00.000000'
>>>
>>> #How can I do this?
>>> datetime.datetime.magic()
'2010-08-03T10:00:00.000000-07:00'

Solution

  • To get the current time in UTC in Python 3.2+:

    >>> from datetime import datetime, timezone
    >>> datetime.now(timezone.utc).isoformat()
    '2015-01-27T05:57:31.399861+00:00'
    

    To get local time in Python 3.3+:

    >>> from datetime import datetime, timezone
    >>> datetime.now(timezone.utc).astimezone().isoformat()
    '2015-01-27T06:59:17.125448+01:00'
    

    Explanation: datetime.now(timezone.utc) produces a timezone aware datetime object in UTC time. astimezone() then changes the timezone of the datetime object, to the system's locale timezone if called with no arguments. Timezone aware datetime objects then produce the correct ISO format automatically.