Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python ISO 8601 date format

i'm trying to format the date like this,

2015-12-02T12:57:17+00:00

here's my code

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

which gives this result,

2015-12-02T12:57:17+0000

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?

like image 332
user3768071 Avatar asked Oct 19 '22 21:10

user3768071


2 Answers

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
        self.name = 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):
         return self.name

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

print datetime.utcnow().strftime('%m/%d/%Y %H:%M:%S %Z')
print datetime.now(GMT).strftime('%m/%d/%Y %H:%M:%S %Z')
print datetime.now(EST).strftime('%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.

like image 56
Maximiliano Rios Avatar answered Oct 21 '22 16:10

Maximiliano Rios


If the "%z" option is platform dependent, how about you just add your : afterwards?

t_str = time.strftime("%Y-%m-%dT%H:%M:%S%z", time.gmtime())
t_str = t_str if t_str[-3] == ':' else  t_str[:-2] + ':' + t_str[-2:]
like image 35
tglaria Avatar answered Oct 21 '22 17:10

tglaria