Wednesday, 28 February 2018

Python timezone - Day 16(1 day later)


  • pip command,if it doesn't work ,open the python setup goto modify and check the add python to environment variables option python time zone library package,pip3 install pytz
  •   
    import pytz
    import datetime
    country = "Europe/Moscow" #check for the spelling and case sensitivity
    tz_to_display = pytz.timezone(country)
    # print(tz_to_display)
    # print(country)
    print("The time in {} is {}".format(country,datetime.datetime.now(tz=tz_to_display)))
    print("UTC is {}".format(datetime.datetime.utcnow()))
    print("LocalTime here is {}".format(datetime.datetime.now()))
    tz_to_display = pytz.timezone("Singapore")
    print("The time in {} is {}".format("Singapore",datetime.datetime.now(tz=tz_to_display)))
    
    #list of all timezones
    for x in pytz.all_timezones:
        print(x)
    print("=="*50)
    print(pytz.country_names)
    #list of all countries
    for x in pytz.country_names:
        print(x)
    
    for x in sorted(pytz.country_names):
        print(x + ": " + pytz.country_names[x])
    
    #although the below code will run,there will be error ,since the few countries
    #like (Bouvet Island ) have not defined the timezones
    # for x in sorted(pytz.country_names):
    #     print("{} : {} : {}".format(x,pytz.country_names[x],pytz.country_timezones(x)))
    
    print("=================="*10)
    #we can use the get method to avoid the below issue
    for x in sorted(pytz.country_names):
        print("{} : {} : {}".format(x,pytz.country_names[x],pytz.country_timezones.get(x)))
    print("*************"*10)
    #we can also use the below method
    for x in sorted(pytz.country_names):
        print("{} : {} ".format(x,pytz.country_names[x],end = ' '))
        if x in (pytz.country_timezones):
            print(pytz.country_timezones[x])
        else:
            print("TimeZone Not Defined")
     
    

    No comments:

    Post a Comment