0

This date format 2018-11-11 01:54:16+00:00 should be converted to Nov 11, 2018 7:24:16 AM GMT+0530

Input : 2018-11-11 01:54:16+00:00
Expected : Nov 11, 2018 7:24:16 AM GMT+0530
Actual :  Nov 11, 2018 07:24:16 AM IST+0530

I'm able to convert the time but not Time-zone as specified above Expected & Actual (GMT & IST) . Below snippet details :

from pytz import timezone
from dateutil import parser
from datetime import datetime

fmt = "%b %d, %Y %H:%M:%S %p %Z%z"
dt = '2018-11-11 01:54:16+00:00'
tmp = parser.parse(dt)
t1 = tmp.astimezone(timezone('Asia/Kolkata'))
print t1 #prints "2018-11-11 07:24:16+05:30"
print t1.strftime(fmt) #prints "Nov 11, 2018 07:24:16 AM IST+0530"

t1 = tmp.astimezone(timezone('GMT'))
print t1.strftime(fmt)    #prints "Nov 11, 2018 01:54:16 AM GMT+0000"

Am I missing something to print GMT (instead of IST) ?

Nov 11, 2018 7:24:16 AM GMT+0530
StackGuru
  • 471
  • 1
  • 9
  • 25
  • Possible duplicate of [How to convert a datetime from one arbitrary timezone to another arbitrary timezone](https://stackoverflow.com/questions/36362381/how-to-convert-a-datetime-from-one-arbitrary-timezone-to-another-arbitrary-timez) – Patrick Artner Nov 11 '18 at 08:24

1 Answers1

1

I think the Arrow module would suit this best;

>>> import arrow
>>> utc = arrow.utcnow()
>>> utc
<Arrow [2013-05-11T21:23:58.970460+00:00]>

>>> utc = utc.shift(hours=-1)
>>> utc
<Arrow [2013-05-11T20:23:58.970460+00:00]>

>>> local = utc.to('US/Pacific')
>>> local
<Arrow [2013-05-11T13:23:58.970460-07:00]>

Specific to your needs this works fine;

>>> asia = arrow.now('Asia/Kolkata')
>>> asia.to('GMT').format("MMM D, YYYY HH:mm:ss A ZZ")

'Nov 11, 2018 10:01:24 AM +00:00'

Try the docs; this is very powerful and easy to use module.

Jamie Lindsey
  • 928
  • 14
  • 26
  • As I posted my code above, i'm getting desired result. But with just a little time difference, Input : 2018-11-11 01:54:16+00:00 , Expected : Nov 11, 2018 7:24:16 AM GMT+0530, Actual : Nov 11, 2018 07:24:16 AM IST+0530 . It's between text IST & GMT. – StackGuru Nov 11 '18 at 09:57
  • ok... just try the arrow library i assure you will be amazed at its ease – Jamie Lindsey Nov 11 '18 at 09:59
  • Thanks @Jack. Looking at arrow library. Any luck with above code ? I guess slight correction needed. – StackGuru Nov 11 '18 at 10:00
  • It should be either UTC+0530 or GMT+0530, which is equivalent to IST https://www.timeanddate.com/time/current-number-time-zones.html – StackGuru Nov 11 '18 at 10:22