Python datetime and pytz module with Examples

Posted in

Python datetime and pytz module with Examples
vinaykhatri

Vinay Khatri
Last updated on December 25, 2024

    In this tutorial, we will discuss the Python datetime module and learn how to deal with date and time in Python.

    Python datetime module

    Python has an inbuilt module datetime, which deals with the date and time. With the help of this module, we can use the time and date in our program. There are many methods associated with the datetime module.

    Let’s have a look at some of the most important.

    datetime module to get the current date and time:

    import datetime
    current_date_nd_time = datetime.datetime.now()
    print(current_date_nd_time)

    Output:

    2019-08-02 20:34:54.969255

    You can also read our article about How to get the Current Date and Time with Python .

    Behind the code

    We use the datetime.now() method of datetime to get the current date and time. The datetime.now() method returns a datetime object as the current date and time. In the above output, 2019-08-02 is the date in the form of yyyy-mm-dd and 20:34:54.969255 in the form of hh-mm-ss.ss

    datetime module to get only the current date

    Example :

    import datetime
    today_date = datetime.date.today()
    print('its:',today_date)

    Output:

    its: 2019-08-02

    Behind the code

    The datetime.date.today() method returns the local date in the form of yyyy-mm-dd.

    Datetime all inbuilt classes

    As datetime is a module, it contains many .py files, meaning it must have many built-in classes.

    Let’s see all the classes defined in the datetime module. We will use the dir() method to print out all the classes defined in the datetime module:

    Example:

    import datetime
    print(dir(datetime))

    Output:

    ['MAXYEAR', 'MINYEAR', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'date', 'datetime', 'datetime_CAPI', 'time', 'timedelta', 'timezone', 'tzinfo']

    The most common classes of datetime modules are:

    • date
    • datetime
    • time
    • timezone
    • timedelta

    datetime module date class (datetime.date)

    As we know, the datetime module has many inbuilt classes, and date is one of them. With the help of this date class, we can perform many tasks.

    Let’s see some examples of the datetime date class.

    1. Use datetime.date to create a datetime object

    With the help of datetime.date, we can create a datetime object and define a date.

    Example:

    from datetime import date
    sam_DOB = date(1999,11,26)
    
    print("Sam date of birth is:", sam_DOB)
    print('the data type if sam_DOB variable is',type(sam_DOB))

    Output:

    Sam date of birth is: 1999-11-26
    the data type if sam_DOB variable is <class 'datetime.date'>

    Behind the code

    We import the date class from the datetime module, and with the help of date(), we create a date object. The date() class accepts three arguments: year, month, and day to create a date object.

    2. date class methods

    In one of the above examples, we have used the date.today() method to print the current date. What if we want only the particular year, month, and day from the day.today() object. For this, we can use that datetime object to access special attributes from the date class, which are obj.year, obj.month and obj.day.

    Example :

    from datetime import date
    today_date = date.today()    #datetime.date object by python for current date
    sam_DOB = date(1999,11,26)   #datetime.date object created by user specified date
    
    print("Sam date of birth year is:", sam_DOB.year)
    print("We are in:", today_date.year)
    
    print("sam date of birth month is:", sam_DOB.month)
    print("Today is:", today_date.day)

    Output:

    Sam date of birth year is: 1999
    We are in: 2019
    sam date of birth month is: 11
    Today is: 2

    Datetime time Class (datetime.time)

    The datetime module contains a time class that deals with time in Hours, minutes, seconds, and microseconds. In one of the above examples, when we printed out today’s complete date with the current time, the time was formatted in hour:minutes:seconds:microsecond.

    1. Lets use the .time() to create datetime.time object

    from datetime import time
    dinner_time = time(21,30,00)
    print("My dinner time is",dinner_time)

    Output:

    My dinner time is 21:30:00

    Behind the code

    Here dinner_time is a time object.

    2. Get hour, minutes, seconds, and Microsecond from a time object.

    With the help of hour, minute, second, and microsecond, we can grab the specific hours and minutes from the time object:

    Example:

    from datetime import time
    dinner_time = time(21,30,50,98937)
    print('dinner Hour is:' ,dinner_time.hour)
    print('dinner minute is:',dinner_time.minute)
    print('second is:', dinner_time.second)
    print('micro second is:',dinner_time.microsecond)

    Output:

    dinner Hour is: 21
    dinner minute is: 30
    second is: 50
    micro second is: 98937

    datetime datetime class (datetime.datetime) (from datetime import datetime)

    The datetime module has a class with a similar name, datetime; the datetime class is used to deal with both date and time. Let’s see some examples.

    Example:

    from datetime import datetime
    # datetime(year, month, day, hour, minute, second, microsecond)
    datetime_obj = datetime(2019,1,1,10,20,40,12323)
    
    print('year:',datetime_obj.year)
    print('month',datetime_obj.month)
    print('day',datetime_obj.day)
    print('hour',datetime_obj.hour)
    print('minute',datetime_obj.minute)

    Output:

    year: 2019
    month 1
    day 1
    hour 10
    minute 20

    datetime timedelta class(datetime.timedelta) or (from datetime import timedelta)

    timedelta is one of the important and logical concepts of the datetime module; the timedelta determines the difference between two time periods.

    Let’s see some examples:

    Example:

    from datetime import timedelta
    # timedelta(weeks, days, hours, minutes, seconds, microseconds)
    time_1 = timedelta(weeks=10)
    time_2 = timedelta(weeks=2,hours=10,minutes=40)
    time_3 = time_1 - time_2
    print("the time difference between time_1 and time_2 is:",time_3)

    Output:

    the time difference between time_1 and time_2 is: 55 days, 13:20:00

    Python Date formatting

    By default python datetime module and all its classes accept date and time in yyyy-mm-dd hh:mm:ss.ms for and print the date and time in the same format. But in the datetime module, we have a special method, strftime() , to format the date object according to the user's will. We can format the date time in many formats, such as dd/mm/yyyy or yyyy/dd/mm.

    Example:

    from datetime import datetime
    current_date = datetime.now()
    #datetime_object.strftime("%d/%m/%Y, %H:%M:%S")
    change_format_current_date = current_date.strftime("%d/%m/%Y, %H-%M")
    print('default format is: ',current_date)
    print('changed format is: ',change_format_current_date)

    Output:

    default format is:  2019-08-02 23:21:41.907656
    changed format is:  02/08/2019, 23-21

    pytz python timezone module

    Python has a very interesting module pytz, which stands for Python time zone. With the help of this module, we can easily print the date and time of different time zones or countries. This is a third-party library. You might have to download this first. For this, use pip install pytz in your command terminal.

    Let’s see an example:

    Example:

    from datetime import datetime
    import pytz
    
    my_time = datetime.now()
    new_york_time = datetime.now(pytz.timezone('America/New_York'))
    print("My country:", my_time.strftime("date %d/%m/%Y time %H:%M"))
    print('New York:', new_york_time.strftime("date %d/%m/%Y time %H:%M"))

    Output:

    My country: date 02/08/2019 time 23:38
    New York: date 02/08/2019 time 14:08

    Conclusion

    This brings us to the end of the Python datetime and pytz module. While the datetime module comes built-in with Python, you must install the pytz module using the pip install command .

    This article has covered all the classes the datetime module comes with, along with examples. Also, this article helps you install the pytz module and use it to print the date and time of different time zones and countries.

    People are also reading:

    Leave a Comment on this Post

    0 Comments