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
To convert Python datetime to string, use the strftime() function. The strftime() method is a built-in Python method that returns the string representing date and time using date, time, or datetime object.
To do this, we will use the FindSystemTimeZoneById() of TimeZoneInfo class. This function takes Id as a parameter to return the equivalent time in timezone passed. In the example below, we are taking the current system time and converting it into “Central Standard Time”. DateTime currentTime = TimeZoneInfo.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With