Python Datetime Module with Quick Examples

Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python

With the ever-complex lifestyle we have adopted, date and time are extremely important. It is like we’re all slaves to time.

In this Python Datetime Module tutorial, we will see how to work with Python Datetime Module and Python date Objects, Python time Objects, Python datetime Objects, and Python timedelta Objects.

You should refer to Python Date and Time.

So, let’s start the Datetime Module in Python.

Python Datetime Module Overview

Introduction to Python Datetime Module

What is the Python Datetime Module?

The Python datetime module offers functions and classes for working with date and time parsing, formatting, and arithmetic. Let’s start with Python Date Time with Examples.

Two kinds of date and time objects exist- naïve and aware.

A naïve object is easier to deal with and doesn’t have enough information to unambiguously locate itself relative to other date/time objects.

An aware object is more realistic, it knows applicable algorithmic and political time adjustments.

To use this module, we must first import it.

>>> import datetime

It has the following constants:

1. MAXYEAR

MAXYEAR tells us the maximum value a year can take, which is 9999.

>>> datetime.MAXYEAR

Output

9999

2. MINYEAR

The minimum value of year is 1. This is what MINYEAR returns.

>>> datetime.MINYEAR

Output

1

Both MAXYEAR and MINYEAR are of the type integer.

>>> type(datetime.MAXYEAR),type(datetime.MINYEAR)

Output

(<class ‘int’>, <class ‘int’>)

Bonus- type() is of the type type.

>>> type(type)

Output

<class ‘type’>

Other than these constants, the datetime has these datetime class types:

1. class datetime.date

Python date is an idealized naïve date considering the current Gregorian calendar.
Attributes: year, month, and day.

2. class datetime.time

Python time is an idealized time, independent of any particular day. Here, we assume that each day is made of exactly 24*60*60 seconds (no leap seconds).
Attributes: hour, minute, second, microsecond, and tzinfo.

3. class datetime.datetime

When you combine a date and a time, you get a datetime.

>>> issubclass(datetime.datetime,datetime.date)

Output

True
>>> issubclass(datetime.datetime,datetime.time)

Output

False

Attributes: year, month, day, hour, minute, second, microsecond, and tzinfo.

4. class datetime.timedelta

A timedelta is a duration expressing the difference between two date, time, or datetime instances to microsecond resolution.

5. class datetime.tzinfo

tzinfo is an abstract base class we use for time zone information objects. The date and time classes use it to provide a customizable notion of time adjustment (for example, to account for time zone and/or DST(daylight saving time)).

6. class datetime.timezone

timezone implements the tzinfo abstract base class as a fixed offset from UTC.

Such objects are immutable. Also, objects of the type ‘date’ are naïve, but those of the types ‘time’ or ‘datetime’ may be aware or naïve.

The next in the Python Datetime Module Tutorial is Date Objects

Python Date Objects

A date object in Python represents a date with year, month, and day, according to the ideal Gregorian calendar.
With a date object, we have the following methods:

1. date(year, month, day) method in python

This method will create an object of type ‘date’.

>>> d=datetime.date(2018,2,28)

Here, year can be from MAXYEAR to MINYEAR, and the month can be from 1 to 12. The day can be from 1 to the number of days in the given month for the given year.

2. today() method in python

today() will return the current local date.

>>> datetime.date.today()

Output

datetime.date(2018, 2, 28)

3. fromtimestamp(timestamp) method in python

fromtimestamp will return the date for the Python timestamp provided.

>>> import time
>>> time.time()

Output

1519818814.358453
>>> datetime.date.fromtimestamp(time.time())

Output

datetime.date(2018, 2, 28)
>>> datetime.date.fromtimestamp(time.time()+999999)

Output

datetime.date(2018, 3, 12)

The date class also has these attributes:

1. date.min in Python

It returns the earliest representable date.

>>> datetime.date.min

Output

datetime.date(1, 1, 1)

2. date.max in Python

Like min, max returns the latest representable date.

>>> datetime.date.max

Output

datetime.date(9999, 12, 31)

3. date.resolution in Python

resolution returns the smallest possible difference between non-equal date objects.

>>> datetime.date.resolution

Output

datetime.timedelta(1)

We also have the following instance attributes:

1. year attribute in Python

This returns the year from a date object.

>>> d=datetime.date(2018,2,28)
>>> d.year

Output

2018

2. month attribute in Python

month returns the month from a date object.

>>> d.month

Output

2

3. day attribute in Python

This returns the day from a date object.

>>> d.day

Output

28

And then, we have the following instance methods:

1. replace(year, month, day) method in python

This will let us update any or all of these three values.

>>> d=d.replace(month=3,day=1)
>>> d

Output

datetime.date(2018, 3, 1)

2. timetuple() method in python

timetuple() returns a tuple of attributes for the current local time.

>>> d.timetuple()

Output

time.struct_time(tm_year=2018, tm_mon=2, tm_mday=28, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=59, tm_isdst=-1)

3. weekday() method in python

weekday() will return the day of the week, where 0 denotes Monday.

>>> d.weekday()

Output

2

4. isoweekday() method in python

Here, Monday is 1.

>>> d.isoweekday()

Output

3

5. isocalendar() method in python

This method returns a tuple of three things- ISO year, ISO week number, and ISO weekday.

>>> d.isocalendar()

Output

(2018, 9, 3)

6. isoformat() method in python

This returns the date in the ISO format.

>>> d.isoformat()

Output

‘2018-02-28’

7. __str__() method in python

This will return the current local date as a string.

>>> d.__str__()

Output

‘2018-02-28’
>>> str(d)

Output

‘2018-02-28’

8. ctime() method in python

ctime returns the current local date in a string format.

>>> d.ctime()

Output

‘Wed Feb 28 00:00:00 2018’

We can also perform some operations on a date object:

>>> d=datetime.date(2018,12,30)
>>> td=datetime.timedelta(0,99999)
>>> d1=d+td
>>> d1

Output

datetime.date(2018, 12, 31)
>>> d1<d

Output

False

The Next in Python Datetime Module Tutorial is Time Objects

Python Time Objects

A time object represents a local time of day. Its arguments are- hour, minute, second, microsecond, and tzinfo.

>>> t=datetime.time(11,59,59,99999)

The class time has the following attributes:

1. min attribute in Python time

This returns the earliest representable time.

>>> t.min

Output

datetime.time(0, 0)

2. max attribute in Python time

This returns the latest representable time.

>>> t.max

Output

datetime.time(23, 59, 59, 999999)

3. resolution attribute in Python time

resolution returns the smallest possible difference between non-equal time objects.

>>> t.resolution

Output

datetime.timedelta(0, 0, 1)

Now, let’s look at some non-readable instance attributes:

1. hour attribute in Python time

This tells us the hour from the object.

>>> t.hour

Output

11

2. minute attribute in Python time

This returns the minute.

>>> t.minute

Output

59

3. second attribute in Python time

This returns the second.

>>> t.second

Output

59

4. microsecond attribute in Python time

This returns the microsecond.

>>> t.microsecond

Output

99999

5. tzinfo attribute in Python time

This returns whatever we pass as tzinfo to the object while creating it. If we didn’t, it returns None.

>>> print(t.tzinfo)

Output

None

6. fold attribute in Python time

This disambiguates wall times during a repeated interval.

>>> t.fold

We have the following instance methods:

1. replace() method in python

This does the same as for ‘date’ objects.

>>> t=t.replace(hour=22,second=7)

2. isoformat() method in python

This method returns the time in the object in the ISO format.

>>> t.isoformat()

Output

’22:59:07.099999′

3. __str__() method in python

This does the same as it does for ‘date’ objects.

>>> t.__str__()

Output

’22:59:07.099999′

Now in the Python Datetime Module Tutorial Lets move ahead with datetime Objects

Python datetime Objects

A datetime object knows about the date and the time. Arguments include year, month, day, hour, minute, second, microsecond, and tzinfo.

>>> d=datetime.datetime(1995,12,31,10,0)

We have the following methods:

1. today() method in python datetime

This method returns the current local datetime.

>>> datetime.datetime.today()

Output

datetime.datetime(2018, 2, 28, 19, 9, 40, 751445)

2. now() method in python datetime

now() returns the current local date and time, but is more precise than today().

>>> datetime.datetime.now()

Output

datetime.datetime(2018, 2, 28, 19, 12, 45, 710542)

3. utcnow() method in python datetime

utcnow() returns the current UTC time.

>>> datetime.datetime.utcnow()

Output

datetime.datetime(2018, 2, 28, 13, 49, 14, 486367)

4. fromtimestamp() method in python datetime

This returns the date and time for the provided timestamp.

>>> datetime.datetime.fromtimestamp(time.time())

Output

datetime.datetime(2018, 2, 28, 19, 20, 24, 55451)

5. utctimestamp() method in python datetime

This is like the previous one, but it returns the UTC time.

>>> datetime.datetime.utcfromtimestamp(time.time())

Output

datetime.datetime(2018, 2, 28, 13, 51, 56, 615793)

Now, let’s look at the class attributes:

1. min attribute in Python datetime

Like for everything else, this returns the earliest representable datetime.

>>> datetime.datetime.min

Output

datetime.datetime(1, 1, 1, 0, 0)

2. max attribute in Python datetime

max returns the latest representable datetime.

>>> datetime.datetime.max

Output

datetime.datetime(9999, 12, 31, 23, 59, 59, 999999)

3. resolution attribute in Python datetime

Resolution is about the smallest possible difference between non-equal datetime objects.

>>> datetime.datetime.resolution

Output

datetime.timedelta(0, 0, 1)

Now, let’s see some read-only instance attributes:

1. year attribute in Python datetime

This returns the year.

>>> d.year

Output

1995

2. month attribute in Python datetime

This returns the month.

>>> d.month

Output

12

3. day attribute in Python datetime

This returns the day.

>>> d.day

Output

31

4. hour attribute in Python datetime

This returns the hour.

>>> d.hour

Output

10

5. minute attribute in Python datetime

This returns the minute.

>>> d.minute

6. second attribute in Python datetime

This returns the second.

>>> d.second

7. microsecond attribute in Python datetime

This returns the microsecond.

>>> d.microsecond

8. tzinfo attribute in Python datetime

This returns the tzinfo; None, if we passed none while creating the object.

>>> print(d.tzinfo)

Output

None

9. fold attribute in Python datetime

This is the same as we discussed before.

>>> d.fold

Finally, let’s try some instance methods.

1. replace() method in python datetime

Again, this is like we have been doing so far.

>>> d.replace(microsecond=7)

Output

datetime.datetime(1995, 12, 31, 10, 0, 0, 7)

2. date() method in python datetime

date() returns a date object from the datetime object.

>>> d.date()

Output

datetime.date(1995, 12, 31)

3. time() method in python datetime

time() returns a time object from the datetime object.

>>> d.time()

Output

datetime.time(10, 0)

4. timetz() method in python datetime

Other than what time() does, timetz() also returns the tzinfo value.

>>> d.timetz()

Output

datetime.time(10, 0)

5. astimezone() method in python datetime

This returns a datetime object with new tzinfo attribute tz, adjusting the date and time data so the result is the same UTC time as self, but in tz’s local time.

>>> d.astimezone()

Output

datetime.datetime(1995, 12, 31, 10, 0, tzinfo=datetime.timezone(datetime.timedelta(0, 19800), ‘India Standard Time’))

6. utcoffset() method in python datetime

If there is a UTC offset, it returns that, else, None.

>>> print(d.utcoffset())

Output

None

7. dst() method in python datetime

If Daylight Savings Time applies, it returns its magnitude.

>>> print(d.dst())

Output

None

8. tzname() method in python datetime

If you had set tzinfo, this would return its name.

>>> print(d.tzname())

Output

None

9. timetuple() method in python datetime

Like we saw earlier, this returns a time tuple of the object.

>>> d.timetuple()

Output

time.struct_time(tm_year=1995, tm_mon=12, tm_mday=31, tm_hour=10, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=365, tm_isdst=-1)

10. utctimetuple() method in python datetime

This returns a time tuple of the UTC time.

>>> d.utctimetuple()

Output

time.struct_time(tm_year=1995, tm_mon=12, tm_mday=31, tm_hour=10, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=365, tm_isdst=0)

11. timestamp() method in python datetime

This returns the timestamp of the object (in seconds).

>>> d.timestamp()

Output

820384200.0

12. weekday() method in python datetime

This returns the number of weekdays for the object, where 0 is for Monday.

>>> d.weekday()

Output

6

#A Sunday

13. isoweekday() method in python datetime

This returns the day of the week, but with Monday as 1.

>>> d.isoweekday()

Output

7

14. isocalendar() method in Python datetime

This returns a tuple of the following: ISO year, ISO week number, ISO weekday.

>>> d.isocalendar()

Output

(1995, 52, 7)

15. isoformat() method in Python datetime

This returns the date and time in the ISO format.

>>> d.isoformat()

Output

‘1995-12-31T10:00:00’

16. __str__() method in python datetime

This returns the date and time in a string representation.

>>> d.__str__()

Output

‘1995-12-31 10:00:00’
>>> str(d)

Output

‘1995-12-31 10:00:00’

17. ctime() method in Python datetime

This, like str, returns the datetime as a string.

>>> d.ctime()

Output

‘Sun Dec 31 10:00:00 1995’

Some operations that we can perform on a datetime object are:

>>> d=datetime.datetime(2018,12,30)
>>> td=datetime.timedelta(0,99999)
>>> d1=d+td
>>> d1

Output

datetime.datetime(2018, 12, 31, 3, 46, 39)
>>> d<d1

Output

True

Python timedelta Objects

A timedelta object represents the duration between two dates or times.

Attributes: days, seconds, microseconds, milliseconds, minutes, hours, weeks

Here, seconds can be from 0 to 86399.

>>> td=datetime.timedelta(9,3,9999,999,58,22,3)

These attributes belong to the timedelta class:

1. min attribute in timedelta

This returns the most negative timedelta object.

>>> datetime.timedelta.min

Output

datetime.timedelta(-999999999)

2. max attribute in timedelta

This one returns the most positive timedelta object.

>>> datetime.timedelta.max

Output

datetime.timedelta(999999999, 86399, 999999)

3. resolution attribute in timedelta

resolution returns the smallest possible difference between non-equal timedelta objects.

>>> datetime.timedelta.resolution

Output

datetime.timedelta(0, 0, 1)

timedelta also supports one instance method:

1. total_seconds() method in python timedelta

This returns the total number of seconds in the duration.

>>> td.total_seconds()

Output

2674684.008999

You can perform arithmetic operations on timedelta objects.

>>> td=datetime.timedelta(0,333)
>>> td1=td*2
>>> td1

Output

datetime.timedelta(0, 666)

So, this was all about the Python Datetime Module Tutorial. Hope you like our explanation.

Python Interview Questions on the Datetime Module

  1. What is the datetime module in Python?
  2. What is datetime datetime now() in Python?
  3. How to print the date and time in Python?
  4. How do you compare two times in Python?
  5. How does Python calculate a datetime difference?

Conclusion

We hope that after this article on Python datetime Module Tutorial, and after Date and Time, you will be able to handle all dates and times easily.

Everyone has to start as a beginner, and it’s perfectly okay if you are verifying the syntax very frequently. The more you use these tools in your own projects, the more natural they will feel.

Work on it twice or thrice. Practice will do it for you. And comment if you need any help with Python Datetime examples.

Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google

courses

DataFlair Team

DataFlair Team creates expert-level guides on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our goal is to empower learners with easy-to-understand content. Explore our resources for career growth and practical learning.

2 Responses

  1. apurva rathore says:

    i don’t understand this example
    >>> d=datetime.date(2020,1,21)
    >>> td=datetime.timedelta(0,99999)
    >>> d1=d+td
    >>> d1

    • DataFlair Team says:

      Hello Apurva,

      Here we are creating a date and storing it in d.
      The timedelta() function is the difference between two dates so we added 99999 seconds to the date d.
      In the result the date has been incremented by one and you will get the result as datetime.date(2020, 1, 22)

Leave a Reply

Your email address will not be published. Required fields are marked *