0

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'))
Saqib
  • 82
  • 7
  • time zone conversion doesn't make much sense for only time, without date (think about DST). I suspect that arrow falls back to LMT (local mean time) of the time zone you're trying to convert to. Try the same with a string that includes a date, this should work correctly. – FObersteiner Feb 13 '21 at 19:04
  • 1
    side-note: afaik, `arrow` internally uses `dateutil`, not `pytz`. – FObersteiner Feb 13 '21 at 19:09
  • I got your idea. Basically, the logic was to store the time with timezone when a user is available for a meeting every week. Saving date along with the time wouldn't help. But, the logic you gave of LMT is correct arrow was using LMT as timezone. – Saqib Feb 13 '21 at 20:17
  • yep, storing the date won't cost you but a few bytes. If it doesn't matter to the user, just don't print it. But internally, you will want to have it. – FObersteiner Feb 13 '21 at 20:23

1 Answers1

2

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
FObersteiner
  • 22,500
  • 8
  • 42
  • 72
  • Should I explicitly add any temporary date in order to convert the timezone? – Saqib Feb 13 '21 at 19:55
  • @Saqib: well it depends, that's why I wrote *appropriate date*. If you have a time zone with DST, you can get different UTC offset depending on what date you choose. – FObersteiner Feb 13 '21 at 19:57