Get Current time for Different Time Zone

Posted in /  

Get Current time for Different Time Zone

Vinay Khatri
Last updated on June 9, 2022

    In this tutorial, we will discuss how we can get the current time of different time zones in Python. Before getting local time for different time zones, let us have a look at how we can get time by using the datetime module.

    Get the Current Time using the strftime Method

    Below is the Python code that uses the strftime methods to output the current time

    from datetime import datetime
    today = datetime.today()
    time = today.strftime("%H:%M")
    print("Its =", time)

    Output:

    Its = 23:02

    Behind the code: In the above example, we have used the strftime() method to extract only hour and minute from the today datetime object. However, the problem with the above code is that the time that we get at the output is a string , which means that we cannot perform different datetime operations on it. For instance, if we want the difference between two time periods, we would do it with the help of string time, and for that we need datetime.time object.

    Get the Current Time using Datetime Object

    Datetime has a special method known as now().time(), which can return the current time. Example:

    from datetime import datetime
    time = datetime.now().time()
    print("Time is =", time)

    Output:

    Time is = 23:16:45.231031

    Behind the code: In the above example, we have used the datetime now().time() method and assigned it to a variable defined as time . Here the time is a datetime.time object, which means we can perform different datetime operations on it.

    Get Local Time for Different Time Zone

    Python has a third-party module called pytz, which is used to get the local time of different time zones. Also, pytz is not a standard Python module, so you have to download it using pip. Example:

    from datetime import datetime
    import pytz
    New_York = pytz.timezone('America/New_York')
    New_York_date_time = datetime.now(New_York)
    print("New York time is:", New_York_date_time.strftime("%H:%M:%S"))
    London = pytz.timezone('Europe/London')
    London_date_and_Time = datetime.now(London)
    print("London time is :", London_date_and_Time.strftime("%H:%M:%S"))

    Output:

    New York time is: 13:59:58
    London time is : 18:59:58

    To Sum it Up

    In this tutorial, we have discussed two different methods, namely strftime() and datetime.now().time() methods to get the current time. Also, we have talked about the pytz module that you can use to get the current time for different time zone. If you have any issues or queries, share them with us in the comments section below.

    Python Tutorials


    Introduction

    Flow Control

    Functions

    Datatypes

    File Handling

    Object & Class

    Additional Tutorials

    Leave a Comment on this Post

    0 Comments