convert python datetime with timezone to string

Brian McCall picture Brian McCall · Apr 13, 2017 · Viewed 13.1k times · Source

I have date time tuples in the format of datetime.datetime(2010, 7, 1, 0, 0, tzinfo=<UTC>)

How can I convert that into a date time string such as 2008-11-10 17:53:59

I am really just getting held up on the tzinfo part.

strftime("%Y-%m-%d %H:%M:%S") works fine without the tzinfo part

Answer

tutuDajuju picture tutuDajuju · Apr 14, 2017

The way you seem to be doing it, would work fine for both timezone aware and naive datetime objects. If you want to also add the timezone to your string, you can simply add add it with %z or %Z, or using the isoformat method:

>>> from datetime import timedelta, datetime, tzinfo

>>> class UTC(tzinfo):
...     def utcoffset(self, dt):
...         return timedelta(0)
... 
...     def dst(self, dt):
...         return timedelta(0)
... 
...     def tzname(self,dt):
...          return "UTC"

>>> source = datetime(2010, 7, 1, 0, 0, tzinfo=UTC())
>>> repr(source)
datetime.datetime(2010, 7, 1, 0, 0, tzinfo=<__main__.UTC object at 0x1054107d0>)

# %Z outputs the tzname
>>> source.strftime("%Y-%m-%d %H:%M:%S %Z")
'2010-07-01 00:00:00 UTC'

# %z outputs the UTC offset in the form +HHMM or -HHMM
>>> source.strftime("%Y-%m-%d %H:%M:%S %z")
'2010-07-01 00:00:00 +0000'

# isoformat outputs the offset as +HH:MM or -HH:MM
>>> source.isoformat()
'2010-07-01T00:00:00+00:00'