views:

635

answers:

3

I have a file. In Python, I would like to take its creation time, and convert it to an ISO time (ISO 8601) string while preserving the fact that it was created in the Eastern Time Zone.

How do I take the file's ctime and convert it to an ISO time string, that indicates the Eastern Time Zone (and takes into account daylight savings time, if necessary)?

+1  A: 

You'll need to use os.stat to get the file creation time and a combination of time.strftime and time.timezone for formatting:

>>> import time
>>> import os
>>> t = os.stat('C:/Path/To/File.txt').st_ctime
>>> t = time.localtime(t)
>>> formatted = time.strftime('%Y-%m-%d %H:%M:%S', t)
>>> tz = str.format('{0:+06.2f}', float(time.timezone) / 3600)
>>> final = formatted + tz
>>> 
>>> final
'2008-11-24 14:46:08-02.00'

EDIT: Switched from gmtime() to localtime().

Max Shawabkeh
Does the timezone account for daylight savings time? It seems like tz will be the same regardless of daylight savings time or not.
Joseph Turian
It will be whatever offset is currently in effect. If DST is active, it will have a different offset from when DST is not.
Max Shawabkeh
+1  A: 

Correct me if I'm wrong (I'm not), but the offset from UTC changes with daylight saving time. So you should use

tz = str.format('{0:+06.2f}', float(time.altzone) / 3600)

I also belive, that the sign should be different

tz = str.format('{0:+06.2f}', -float(time.altzone) / 3600)

I could be wrong, but I don't think so

Jarek Przygódzki
A: 

I agree with Jarek, and I furthermore note that the ISO offset separator character is a colon, so I think the final answer should be:

isodate.datetime_isoformat(datetime.datetime.now()) + str.format('{0:+06.2f}', -float(time.timezone) / 3600).replace('.', ':')
mattborn