I need to print the FULL local date/time in ISO 8601 format, including the local timezone info, eg:
2007-04-05T12:30:00.0000-02:00
I can use datetime.isoformat()
to print it, if I have the right tzinfo object - but how do I get that?
Note, I'm stuck at Python 2.5, which may reduce some availability of options.
I've worked out my own way to do this, hopefully this will be useful to anyone else wanting to print useful timestamps in output files.
import datetime
# get current local time and utc time
localnow = datetime.datetime.now()
utcnow = datetime.datetime.utcnow()
# compute the time difference in seconds
tzd = localnow - utcnow
secs = tzd.days * 24 * 3600 + tzd.seconds
# get a positive or negative prefix
prefix = '+'
if secs < 0:
prefix = '-'
secs = abs(secs)
# print the local time with the difference, correctly formatted
suffix = "%s%02d:%02d" % (prefix, secs/3600, secs/60%60)
now = localnow.replace(microsecond=0)
print "%s%s" % (now.isoformat(' '), suffix)
This feels a little hacky, but seems the only reliable way to get a local time with the correct UTC offset. Better answers welcome!