Wednesday, January 9, 2013

Standard time format ISO 8601

I'm often forgetting what this standard is. Here are some code snippets to generate ISO 8601 compliant datetime strings.

Python
In [8]: import time

In [9]: time.strftime('%Y-%m-%dT%H:%M:%S%z')
Out[9]: '2013-01-09T17:58:37-0800'
Python datetime, which has dumb handling of timezones, easiest is to just get a UTC time and hard-code in the Z for Zulu:
In [39]: datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')
Out[39]: '2013-01-10T02:09:17Z'
Ruby
$ irb
irb(main):001:0> require 'time'
=> true
irb(main):002:0> Time.now.iso8601
=> "2013-01-09T17:55:01-08:00"
Bash
$ date +%Y-%m-%dT%H:%M:%S%z
2013-01-09T17:59:41-0800
As an aside, python uses the old and incredibly confusing UNIX convention for timezones (man tzset) that is seconds West of UTC (e.g. Pacific US is +28800 currently), whereas basically everything else these days uses hours and minutes East of UTC (Pacific US is -0800 currently).

Here's what it looks like:
In [46]: time.timezone
Out[46]: 28800

In [47]: time.timezone/3600
Out[47]: 8

No comments: