user3768071 user3768071 - 1 year ago 192
Python Question

python ISO 8601 date format

i'm trying to format the date like this,


here's my code

time.strftime("%Y-%m-%dT%H:%M:%S%z", time.gmtime())

which gives this result,


i can't see any other variations of %z that can provide the correct format of +00:00 ? what's the correct way to go about this?

Answer Source

That can work for you:

Python - Convert UTC datetime string to local datetime

I copied the code to make it easier to tackle, I indicate it's another person's answer anyway.

from datetime import datetime,tzinfo,timedelta

class Zone(tzinfo):
    def __init__(self,offset,isdst,name):
        self.offset = offset
        self.isdst = isdst = name
    def utcoffset(self, dt):
        return timedelta(hours=self.offset) + self.dst(dt)
    def dst(self, dt):
            return timedelta(hours=1) if self.isdst else timedelta(0)
    def tzname(self,dt):

GMT = Zone(0,False,'GMT')
EST = Zone(-5,False,'EST')

print datetime.utcnow().strftime('%m/%d/%Y %H:%M:%S %Z')
print'%m/%d/%Y %H:%M:%S %Z')
print'%m/%d/%Y %H:%M:%S %Z')

t = datetime.strptime('2011-01-21 02:37:21','%Y-%m-%d %H:%M:%S')
t = t.replace(tzinfo=GMT)
print t
print t.astimezone(EST)

I've tried it in my Python Notebook and works perfectly.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download