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?
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.
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:]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With