I am tweaking my yt-reco, trying to add a <time/> for the generation time, and I am still having problems with Python’s date/time.
It turns out not so difficult if you ain’t going to convert between two different timezone, but just local to UTC. You don’t even need to use third-party libraries. Here is the code:
>>> import datetime as dt
>>> import time
>>> TMPL = "<time datetime='{datetime}'>{now}</time>"
>>> now = dt.datetime.now()
>>> utc = dt.datetime.utcfromtimestamp(
... time.mktime(now.timetuple()))
>>> print(TMPL.format(datetimet=utc.isoformat() + 'Z',
... now=now.ctime()))
<time datetime='2013-11-13T21:59:47Z'>Thu Nov 13 13:59:47 2013</time>
The .isoformat() produces a RFC 3339 or ISO 8601 valid string and ctime() for representing. I could have just use .now() and .utcnow() to have two datetime objects, but since there is microseconds and possibly fall into different seconds during the two calls. The code only use standard Python library.
The microsecond is lost in translation, if you insist to keep it, then:
>>> utc = dt.datetime.utcfromtimestamp(
... time.mktime(now.timetuple())
... ).replace(microsecond=now.microsecond)
If you don’t like UTC, then, with dateutil library:
>>> from dateutil.tz import tzlocal
>>> now = dt.datetime.now(tzlocal())
>>> print(TMPL.format(datetime=now.isoformat(),
... now=now.ctime()))
<time datetime='2013-11-13T14:10:57.258846-08:00'>Thu Nov 13 14:10:57 2013</time>
Note that you don’t have to have timezone offset in datetime attribute, however, it could become an issue if you don’t mean that as local time in visitor’s system.
I have been coding in Python for years, never could remember or be sure what to do when date/time is involved, it’s like being caught in space-time paradox, nothing is clear to me. I hope another decade, Python would have simple way to deal with time and I am not even hoping about easy timezone conversion.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.