Python datetime module with examples

Python Methods and Functions

The Datetime module provides classes for working with dates and times. These classes provide a number of functions for working with dates, times, and time intervals. Date and datetime are objects in Python, so when you manipulate them you are actually manipulating objects, not strings or timestamps.

The datetime classes are divided into 6 main classes:

  • date — an idealized naive date, provided that the current Gregorian calendar has always been and will always be in force. Its attributes are year, month and day.
  • time — idealized time, independent of any particular day, provided that each day has exactly 24 * 60 * 60 seconds. Its attributes are hours, minutes, seconds, microseconds, and tzinfo.
  • datetime — it is a combination of date and time along with the attributes of year, month, day, hour, minute, second, microsecond, and tzinfo.
  • timedelta — duration, which expresses the difference between two instances of a date, time, or date and time in microsecond resolution.
  • tzinfo — provides information about timezones .
  • timezone — class that implements the abstract base class tzinfo as a fixed offset from UTC (New in version 3.2).

Date class

When an object of this class is created, it represents a date in the format YYYY-MM-DD . The constructor of this class needs three required arguments year, month, and date.

Constructor syntax:

 class datetime.date (year, month, day) 

Arguments must be in the following range —

  • MINYEAR 1 1

    Note. If the argument is not an integer, it will call TypeError and if it is out of range, a ValueError will be generated.

    # Python program for
    # show date class

     
    # import date class

    from datetime import date

     
    # initializing constructor
    # and passing arguments to
    # format year, month, date

    my_date = date ( 1996 , 12 , 11 )

     

    print ( "Date passed as argument is" , my_date)

     
    # Uncommenting my_date = date (1996, 12, 39)
    # will raise a ValueError as is
    # out of range

     
    # uncommenting my _date = date (& # 39; 1996 & # 39 ;, 12, 11)
    # will raise a TypeError as a string
    # passed instead of interger

    Exit :

     Date passed as argument is 1996-12-11 
     Traceback (most recent call last): File "/home/ccabfb570d9bd1dcd11dc4fe55fd6ba2.py", line 14, in my_date = date (1996, 12, 39) ValueError: day is out of range for month Traceback (most recent call last): File "/home/53b974e10651f1853eee3c004b48c481.py", line 18, in my_date = date ('1996', 12, 11) TypeError: an integer is required (got type str) 

    Current date

    To return the current local date today () date class function. The today () function has several attributes (year, month, and day). They can be printed individually.

    # Python program for
    # print the current date

     

    from datetime import date

      
    # calling today
    # date class function

    today = date.today ()

     

    print ( "Today's date is" , today)

     
    # Print date components

    print ( "Date components " , today.year, today.month, today.day)

    Exit :

     Today's date is 2019-10-25 Date components 2019 10 25 

    Various functions available in the date class:

    Function name Description
    fromtimestamp (timestamp) Return the local date corresponding to the POSIX timestamp
    fromordinal (ordinal) Return the date corresponding to the proleptic Gregorian ordinal, where January 1 of year 1 has ordinal 1.
    fromisoformat(date_string) Return a date corresponding to a date_string given in the format YYYY-MM-DD:
    fromisocalendar (year, week, day) R eturn a date corresponding to the ISO calendar date specified by year, week and day.

    Time Lesson

    The time object is the local time, regardless of any day.
    Constructor syntax:

     class datetime.time (hour = 0, minute = 0, second = 0, microsecond = 0, tzinfo = None, *, fold = 0) 

    All arguments are optional. tzinfo can be None otherwise all attributes must be integer in the following range —

    • 0 0 0 0 times in [0, 1]

    # Python program for
    # demonstrate class times

     

    from datetime import time

      
    # constructor call

    my_time = time ( 13 , 24 , 56 )

     

    print ( "Entered time" , my_time)

     
    # constructor call with 1
    # argument

    my_time = time (minute = 12 )

    print ( "Time with one argument" , my_time)

     
    # Call constructor with
    # 0 argument

    my_time = time ()

    print ( "Time without argument" , my_time)

      
    # Uncommented time (hour = 26)
    # will generate a ValueError as
    # this is out of range

     
    # comment time (hour = & # 39; 23 & # 39;)
    # will raise a TypeError as
    # string is passed instead of int

    Output:

     Entered time 13:24:56 Time with one argument 00:12:00 Time without argument 00:00:00 
     Traceback (most recent call last): File "/ home / 95ff83138a1b3e67731e57ec6dddef25.py ", line 21, in print (time (hour = 26)) ValueError: hour must be in 0..23 Traceback (most recent call last): File" /home/fcee9ba5615b0b74fc3ba39ec9a789fd.py ", line 21, in print (time (hour =' 23')) TypeError: an integer is required (got type str) 

    Once a time object is created, its attributes can also be printed separately.

    from datetime import time

      

    Time = time ( 11 , 34 , 56 )

     

    print ( "hour =" , Time.hour)

    print ( "minute =" , Time.minute)

    print ( " second = " , Time.second)

    print ( "microsecond =" , Time.microsecond)

    Exit :

     hour = 11 minute = 34 second = 56 microsecond = 0 

    Date and time

    Date and time information is contained in this class. Like a date object, datetime assumes that the current Gregorian calendar is used in both directions; like a time object, datetime assumes there are exactly 3600 * 24 seconds each day.

    Constructor syntax:

    class datetime.datetime (year , month, day, hour = 0, minute = 0, second = 0, microsecond = 0, tzinfo = None, *, fold = 0)

    Year, month, and day are required ... tzinfo can be None , other attributes must be integers in the following range —

    • MINYEAR 1 1 0 0 0 0 times in [0, 1]

    Note — Passing an argument other than an integer will raise TypeError and passign arguments out of range will raise ValueError .

    # Python program for
    # demonstrate a datetime object

     

    from datetime import datetime

     
    # Initializing constructor

    a = datetime ( 1999 , 12 , 12 )

    prin t (a)

     
    # Initializing constructor
    # with time parameters

    a = datetime ( 1999 , 12 , 12 , 12 , 12 , 12 , 342380 )

    print (a)

    Exit :

     1999-12-12 00: 00:00 1999-12-12 12: 12: 12.342380 

    After creating a datetime object, its attributes can also be print separately.

    from datetime import datetime

     

    a = datetime ( 1999 , 12 , 12 , 12 , 12 , 12 )

     

    print ( "year =" , a.year)

    print ( "month =" , a.month)

    print ( "hour =" , a.hour)

    print ( "minute =" , a.minute)

    print ( "timestamp =" , a.timestamp ())

    Exit:

     year = 1999 month = 12 hour = 12 minute = 12 timestamp = 945000732.0 

    Current date and time

    You can print the current date and time using the now () function . The now () function returns the current local date and time.

    from datetime import datetime

     
    # Call now () function

    today = datetime.now ()

     

    print ( "Current date and time is" , today)

    Exit:

     Current date and time is 2019-10-25 11: 12: 11.289834 

    Other functions of the datetime class —

    Fucntion name Description
    utcnow () Return the current UTC date and time, with tzinfo None.
    fromtimestamp (timestamp, tz = None) Return the local date and time corresponding to the POSIX timestamp.
    utcfromtimestamp (timestamp) Return the UTC datetime corresponding to the POSIX timestamp, with tzinfo None.
    fromordinal (ordinal) Return the datetime corresponding to the proleptic Gregorian ordinal, where January 1 of year 1 has ordinal 1.
    combine (date, time, tzinfo = self.tzinfo) Return a new datetime object whose date components are equal to the given date object's, and whose time components are equal to the given time object's .
    fromisoformat (date_string) Return a datetime corresponding to a date_string in one of the formats emitted by date.isoformat () and datetime.isoformat ( ).
    strptime (date_string, format) Return a datetime corresponding to date_string, parsed according to format.

    Timedelta class

    Python's timedelta () function is present in the datetime library, which is commonly used to calculate date differences, and can also be used to manipulate dates in Python. This is one of the simplest ways to manipulate dates.

    Constructor syntax:

    class datetime.timedelta (days = 0, seconds = 0, microseconds = 0, milliseconds = 0, minutes = 0, hours = 0, weeks = 0)

    Returns: Date

    # Demonstration of the Timedelta function

     

    from datetime import datetime, timedelta 

     

     
    # Using the current time

    ini_time_for_now = datetime.now () 

     
    # print initial_date

    print ( "initial_date" , str (ini_time_for_now)) 

     
    # Calculating future dates
    # two years

    future_date_after_2yrs = ini_time_for_now + timedelta (days = 730

     

    future_date_after_2days = ini_time_for_now + timedelta (days = 2

     
    # printing future dates are calculated

    print ( 'future_date_after_2yrs:' , str (future_date_after_2yrs)) 

    print ( ' future_date_after_2days: ' , str (future_date_after_2days)) 

    Output:

     initial_date 2019-10-25 12: 01: 01.227848 future_date_after_2yrs: 2021-10-24 12: 01: 01.227848 future_date_after_2days: 2019-10-27 12: 01: 01.227848 

    The time difference can also be found using this class.

    # Timedelta function demo

    from datetime import datetime, timedelta 

     
    # Using the current time

    ini_time_for_now = datetime.now () 

     
    # print initial_date

    print ( "initial_date" , str (ini_time_for_now)) 

     
    # Some other time

    new_final_time = ini_time_for_now +  

    timedelta (days = 2

      
    # print new final_date

    print ( "new_final_time" , str (new_final_time)) 

     

      
    # printing is calculated

    print ( 'Time difference:' , str (new_final_time -  

    ini_time_for_now)) 

    Exit:

     initial_date 2019-10-25 12: 02: 32.799814 new_final_time 2019-10-27 12: 02: 32.7998 14 Time difference: 2 days, 0:00:00 

    Qingfo class

    This is an abstract base class meaning this class should not be created directly. An instance (concrete subclass) of tzinfo can be passed to constructors for date and time objects. The latter objects treat their attributes as local time, and the tzinfo object supports methods that show the local time offset from UTC, time zone name, and DST offset, all relative to the date or time object passed to it. To learn more about this class, click here .

    Timezone

    The timezone class is a subclass of tzinfo, each instance of which represents a timezone defined by a fixed offset from UTC.

    Constructor syntax:

     class datetime.timezone (offset, name = None) 

    The offset argument must be specified as a timedelta object representing the difference between local time and UTC.

    Note. The ValueError will be raised if the offset is not between -timedelta (hours = 24) and timedelta ( hours = 24) .





Get Solution for free from DataCamp guru