Python Datetime Module with Quick Examples

Python course with 57 real-time projects - 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 Python Datetime Module.

Python Datetime Module Overview

Introduction to Python Datetime Module

What is 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, 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 the UTC.

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

The next in Python Datetime Module Tutorial is Date Objects

Python date Objects

A date object 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)

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

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

Here, year can be from MAXYEAR to MINYEAR, and 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()

today() will return the current local date.

>>> datetime.date.today()

Output

datetime.date(2018, 2, 28)

3. fromtimestamp(timestamp)

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

It returns the earliest representable date.

>>> datetime.date.min

Output

datetime.date(1, 1, 1)

2. date.max

Like min, max returns the latest representable date.

>>> datetime.date.max

Output

datetime.date(9999, 12, 31)

3. date.resolution

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

This returns the year from a date object.

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

Output

2018

2. month

month returns the month from a date object.

>>> d.month

Output

2

3. day

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)

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()

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()

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

>>> d.weekday()

Output

2

4. isoweekday()

Here, Monday is 1.

>>> d.isoweekday()

Output

3

5. isocalendar()

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

>>> d.isocalendar()

Output

(2018, 9, 3)

6. isoformat()

This returns the date in the ISO format.

>>> d.isoformat()

Output

‘2018-02-28’

7. __str__()

This will return the current local date as a string.

>>> d.__str__()

Output

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

Output

‘2018-02-28’

8. ctime()

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

This returns the earliest representable time.

>>> t.min

Output

datetime.time(0, 0)

2. max

This returns the latest representable time.

>>> t.max

Output

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

3. resolution

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

This tells us the hour from the object.

>>> t.hour

Output

11

2. minute

This returns the minute.

>>> t.minute

Output

59

3. second

This returns the second.

>>> t.second

Output

59

4. microsecond

This returns the microsecond.

>>> t.microsecond

Output

99999

5. tzinfo

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

This disambiguates wall times during a repeated interval.

>>> t.fold

We have the following instance methods:

1. replace()

This does the same as for ‘date’ objects.

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

2. isoformat()

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

>>> t.isoformat()

Output

’22:59:07.099999′

3. __str__()

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 objects knows about the date and the time. Arguments include year, month, day, hour, minute, second, microsecond, tzinfo.

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

We have the following methods:

1. today()

This method returns the current local datetime.

>>> datetime.datetime.today()

Output

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

2. now()

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()

utcnow() returns the current UTC time.

>>> datetime.datetime.utcnow()

Output

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

4. fromtimestamp()

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()

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

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

>>> datetime.datetime.min

Output

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

2. max

max returns the latest representable datetime.

>>> datetime.datetime.max

Output

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

3. resolution

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

This returns the year.

>>> d.year

Output

1995

2. month

This returns the month.

>>> d.month

Output

12

3. day

This returns the day.

>>> d.day

Output

31

4. hour

This returns the hour.

>>> d.hour

Output

10

5. minute

This returns the minute.

>>> d.minute

6. second

This returns the second.

>>> d.second

7. microsecond

This returns the microsecond.

>>> d.microsecond

8. tzinfo

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

>>> print(d.tzinfo)

Output

None

9. fold

This is the same as we discussed before.

>>> d.fold

Finally, let’s try some instance methods.

1. replace()

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()

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

>>> d.date()

Output

datetime.date(1995, 12, 31)

3. time()

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

>>> d.time()

Output

datetime.time(10, 0)

4. timetz()

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

>>> d.timetz()

Output

datetime.time(10, 0)

5. astimezone()

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()

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

>>> print(d.utcoffset())

Output

None

7. dst()

If Daylight Savings Time applies, it returns its magnitude.

>>> print(d.dst())

Output

None

8. tzname

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

>>> print(d.tzname())

Output

None

9. timetuple()

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()

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()

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

>>> d.timestamp()

Output

820384200.0

12. weekday()

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

>>> d.weekday()

Output

6

#A Sunday

13. isoweekday()

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

>>> d.isoweekday()

Output

7

14. isocalendar()

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

>>> d.isocalendar()

Output

(1995, 52, 7)

15. isoformat()

This returns the date and time in the ISO format.

>>> d.isoformat()

Output

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

16. __str__()

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()

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

This returns the most negative timedelta object.

>>> datetime.timedelta.min

Output

datetime.timedelta(-999999999)

2. max

This one returns the most positive timedelta object.

>>> datetime.timedelta.max

Output

datetime.timedelta(999999999, 86399, 999999)

3. resolution

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()

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 Datetime Module

  1. What is 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 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 date and time easily.

If you think this is a bit too much for once, don’t panic. Work on it twice or thrice. Practice will do it for you. And comment if you need any help on Python Datetime examples.

Did we exceed your expectations?
If Yes, share your valuable feedback on Google

follow dataflair on YouTube

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 *