Sunday, November 1, 2009

Isoformat in Python

As Tim mentions, trying to get the current datetime's isoformat is really ugly in Python. Unfortunately it's a little bit uglier than he described, due to daylight savings time... Here it is.

from datetime import datetime, tzinfo, timedelta
import time

class TZ(tzinfo):
def utcoffset(self,dt): return timedelta(
# begin extra craziness
seconds = -time.altzone\
if time.localtime().tm_isdst\
else -time.timezone)
# end extra craziness

def dst(self,dt): return timedelta(0)

a = datetime.now(TZ())
a= a.replace(microsecond = 0)
print a.isoformat()

That prints
2009-11-01T22:24:30-08:00

Compare with php

date("c")

/* I actually don't know if this handles
daylight savings time or not
but it's still way simpler */

grrr...

No comments: