0

I am trying to convert a datetime from UTC to another timezone. But after the conversion, the time component is not changing. Instead it's adding the offset time along with the timezone.

Is there any way I can display the actual time in that timezone?

Sample code:

>>> import datetime
>>> import pytz
>>> today=datetime.datetime.now()
>>> today
datetime.datetime(2019, 4, 18, 0, 50, 33, 294610)
>>> today.isoformat()
'2019-04-18T00:50:33.294610'
>>> today2=today.astimezone(pytz.timezone('Asia/Singapore'))
>>> today2
datetime.datetime(2019, 4, 18, 0, 50, 33, 294610, tzinfo=<DstTzInfo 'Asia/Singapore' +08+8:00:00 STD>)
>>> today2.isoformat()
'2019-04-18T00:50:33.294610+08:00'
>>> today2.strftime("%Y-%m-%d %H:%M:%S")
'2019-04-18 00:50:33'
>>>

I expect today2 variable to print: 2019-04-18T08:50:33.294610

I tried formatting the date using strftime("%Y-%m-%d %H:%M:%S"), but it's still showing me 2019-04-18 00:50:33.

Please help. Thanks.

ujjaldey
  • 421
  • 2
  • 5
  • 17
  • Try `today.astimezone(timezone('Asia/Singapore')).strftime('%Y-%m-%d %H:%M:%S')` to display the datetime in the specific time zone you want. Remember that the datetime value is always stored in UTC so anytime you want to convert for display, you need to be explicit. – benvc Apr 17 '19 at 17:18

1 Answers1

0

This should do the trick, note that I set the tzinfo=None to remove the +08:00

In [102]: today2.replace(tzinfo=None).isoformat()                                                                                    
Out[102]: '2019-04-18T01:10:32.226014'

In [103]: today2.isoformat()                                                                                                         
Out[103]: '2019-04-18T01:10:32.226014+08:00'
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40
  • Still getting same output.. I expect today2 be like 2019-04-19 00:26:54 ```>>> today2=today.astimezone(pytz.timezone('Asia/Singapore')) >>> today2 datetime.datetime(2019, 4, 18, 20, 26, 54, 333026, tzinfo=) '2019-04-18T20:26:54.333026+08:00' >>> today2.strftime("%Y-%m-%d %H:%M:%S") '2019-04-18 20:26:54' >>> >>> today2.replace(tzinfo=None).isoformat() '2019-04-18T20:26:54.333026' >>> today2.isoformat() '2019-04-18T20:26:54.333026+08:00'``` – ujjaldey Apr 18 '19 at 12:30
  • I gave the answer for python3.x. Are you using that? – Devesh Kumar Singh Apr 18 '19 at 23:51