17

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

Brian McCall
  • 1,831
  • 1
  • 18
  • 33
  • '%z' if you are using `python3` http://stackoverflow.com/questions/26165659/python-timezone-z-directive-for-datetime-strptime-not-available – sobolevn Apr 12 '17 at 23:20
  • the < is giving me an invalid syntax error – Brian McCall Apr 12 '17 at 23:24
  • strftime("%Y-%m-%d %H:%M:%S") works fine for me. Can you give an example about how the time tuples are constructed and what error you got? – Allen Qin Apr 13 '17 at 00:19
  • this would help http://www.saltycrane.com/blog/2009/05/converting-time-zones-datetime-objects-python/ – Bijoy Apr 13 '17 at 03:26
  • I am getting exactly this from the query datetime.datetime(2010, 7, 1, 0, 0, tzinfo=) I am not sure how the tuples are created – Brian McCall Apr 13 '17 at 14:35

1 Answers1

21

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'
tutuDajuju
  • 10,307
  • 6
  • 65
  • 88