Python2 datetime - convert time to UTC by timestamp with offset

I am using Python 2 for reasons beyond my control and therefore cannot move to Python 3 (which has better timezone support).

I have an epoch time like 1492464960.53

and I want to convert it to a timestamp like this 2017-04-17T21:36:00.530000+00:00

.

I tried using the following code, but that doesn't give the +00:00

timestamp part that I need as well.

import datetime
created=1492464960.53
time_str = datetime.datetime.utcfromtimestamp(created).isoformat()
print(time_str)
>> 2017-04-17T21:36:00.530000

      

How to add a part +00:00

?

+3


source to share


2 answers


Just tried this and it worked for me.

First, to explain why the original solution doesn't work, from what I understand, the reason isoformat () won't work for a value above the epoch is because this method requires the object to return something with utcoffset attribute, however above is float value / epoch returns "None" when I tested it with this attribute. The isoformat method can work very well if we are not dealing with float transformations.



Anyway, for a solution:

from datetime import datetime, tzinfo
import pytz
created = 1492464960.53
dt = datetime.utcfromtimestamp(created)

##print results for above 'dt' variable

2017-04-17 21:36:00.530000

dt = dt.replace(tzinfo=pytz.utc)

##print results for above 'dt' variable

2017-04-17 21:36:00.530000+00:00

dt.isoformat()

##print results for above 'dt' variable

'2017-04-17T21:36:00.530000+00:00'

      

+1


source


Sorry not sure if you mean exactly about installing pytz, I just installed pytz and then added an import statement to my python shell on my local machine.

Not sure if this is the best solution, however it looks like it worked, here's an alternative I can suggest:

created = 1492464960.53
dt = dt.utcnow().fromtimestamp(created, dt.tzname()).isoformat()

      

should print



'2017-04-17T14: 36: 00.530000'

from datetime import time
t = time(00, 00, 00, tzinfo=dt.tzname())
tmstmp = dt.isoformat()+'+'+t.strftime("%M:%S %z")

      

should print



2017-04-17T21: 36: 00.530000 + 00: 00

0


source







All Articles