Search code examples
pythonpython-3.xdatetimepytz

Getting current time of different timezone by providing timezone value


In a scenario where I don't know the name of the time zone area, I need to get the current time in a specific timezone. Basically, I need a method where I will pass the UTC value of timezone and expect the return as the current time of the area. the method which I need should be like`

def get_current_time(utc_value):
    #CODE
    return current_time
print (get_current_time("+05:30"))`

And I expect it should give me the current time of UTC +5:30 timezone. How to do it?


Solution

  • from pytz import all_timezones, timezone
    from datetime import datetime
    
    def get_cuurent_time(utc_value):
        for zone in all_timezones:
            tz = timezone(zone)
            if utc_value in  str(datetime.now(tz)):
                return datetime.now(tz)
    print (get_cuurent_time("+05:30"))
    

    I made it, bother not :), but if there is any other way also, please let me know.