pythonpython-3.xpython-datetimepytzpython-arrow

Conversion of timezone of datetime.time


I am writing Python code using arrow library to convert timezone (which will be UTC by default) in the string (without date) to another timezone.

A sample string value is: 18:30+0000

The code snippet is :

start      = '18:30+0000'
start_time = arrow.get(start,'hh:mmZ')

print(start_time.format('hh:mm A ZZ'))

print(start_time.to('Australia/Melbourne').format('hh:mm A ZZ'))
# This should print 05:30 AM +11:00 - but showing 04:09 AM +09:39

I have also tried to convert to other timezones as well.

print(start_time.to('Europe/London').format('hh:mm A ZZ'))
# This should print 06:30 PM +00:00 - but showing 06:28 PM -00:01

Getting UTC now and then converting it to different timezone working perfectly fine

print(arrow.utcnow().to('Australia/Melbourne').format('hh:mm A ZZ'))

SOLUTION: We have to add temporary date value for conversion if we don't have date value.

def convert_timezone(time_to_convert,timezone):
  time_to_convert='20111111 '+time_to_convert
  return arrow.get(time_to_convert).to(timezone)

print(convert_timezone('18:30+0000','Australia/Melbourne').format('hh:mm A ZZ'))

Solution

  • add an appropriate date to the input string and this works as you expect:

    import arrow
    
    start = '2021-02-01 18:30+0000'
    start_time = arrow.get(start)
    print(start_time.to('Australia/Melbourne').format('hh:mm A ZZ'))
    # 05:30 AM +11:00