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 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
2. MINYEAR
The minimum value of year is 1. This is what MINYEAR returns.
>>> datetime.MINYEAR
Output
Both MAXYEAR and MINYEAR are of the type integer.
>>> type(datetime.MAXYEAR),type(datetime.MINYEAR)
Output
Bonus- type() is of the type type.
>>> type(type)
Output
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
>>> issubclass(datetime.datetime,datetime.time)
Output
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
3. fromtimestamp(timestamp)
fromtimestamp will return the date for the Python timestamp provided.
>>> import time >>> time.time()
Output
>>> datetime.date.fromtimestamp(time.time())
Output
>>> datetime.date.fromtimestamp(time.time()+999999)
Output
The date class also has these attributes:
1. date.min
It returns the earliest representable date.
>>> datetime.date.min
Output
2. date.max
Like min, max returns the latest representable date.
>>> datetime.date.max
Output
3. date.resolution
resolution returns the smallest possible difference between non-equal date objects.
>>> datetime.date.resolution
Output
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
2. month
month returns the month from a date object.
>>> d.month
Output
3. day
This returns the day from a date object.
>>> d.day
Output
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
2. timetuple()
timetuple() returns a tuple of attributes for the current local time.
>>> d.timetuple()
Output
3. weekday()
weekday() will return the day of the week, where 0 denotes Monday.
>>> d.weekday()
Output
4. isoweekday()
Here, Monday is 1.
>>> d.isoweekday()
Output
5. isocalendar()
This method returns a tuple of three things- ISO year, ISO week number, and ISO weekday.
>>> d.isocalendar()
Output
6. isoformat()
This returns the date in the ISO format.
>>> d.isoformat()
Output
7. __str__()
This will return the current local date as a string.
>>> d.__str__()
Output
>>> str(d)
Output
8. ctime()
ctime returns the current local date in a string format.
>>> d.ctime()
Output
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
>>> d1<d
Output
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
2. max
This returns the latest representable time.
>>> t.max
Output
3. resolution
resolution returns the smallest possible difference between non-equal time objects.
>>> t.resolution
Output
Now, let’s look at some non-readable instance attributes:
1. hour
This tells us the hour from the object.
>>> t.hour
Output
2. minute
This returns the minute.
>>> t.minute
Output
3. second
This returns the second.
>>> t.second
Output
4. microsecond
This returns the microsecond.
>>> t.microsecond
Output
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
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
3. __str__()
This does the same as it does for ‘date’ objects.
>>> t.__str__()
Output
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
2. now()
now() returns the current local date and time, but is more precise than today().
>>> datetime.datetime.now()
Output
3. utcnow()
utcnow() returns the current UTC time.
>>> datetime.datetime.utcnow()
Output
4. fromtimestamp()
This returns the date and time for the provided timestamp.
>>> datetime.datetime.fromtimestamp(time.time())
Output
5. utctimestamp()
This is like the previous one, but it returns the UTC time.
>>> datetime.datetime.utcfromtimestamp(time.time())
Output
Now, let’s look at the class attributes:
1. min
Like for everything else, this returns the earliest representable datetime.
>>> datetime.datetime.min
Output
2. max
max returns the latest representable datetime.
>>> datetime.datetime.max
Output
3. resolution
Resolution is about the smallest possible difference between non-equal datetime objects.
>>> datetime.datetime.resolution
Output
Now, let’s see some read-only instance attributes:
1. year
This returns the year.
>>> d.year
Output
2. month
This returns the month.
>>> d.month
Output
3. day
This returns the day.
>>> d.day
Output
4. hour
This returns the hour.
>>> d.hour
Output
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
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
2. date()
date() returns a date object from the datetime object.
>>> d.date()
Output
3. time()
time() returns a time object from the datetime object.
>>> d.time()
Output
4. timetz()
Other than what time() does, timetz() also returns the tzinfo value.
>>> d.timetz()
Output
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
6. utcoffset()
If there is a UTC offset, it returns that, else, None.
>>> print(d.utcoffset())
Output
7. dst()
If Daylight Savings Time applies, it returns its magnitude.
>>> print(d.dst())
Output
8. tzname
If you would have set tzinfo, this would return its name.
>>> print(d.tzname())
Output
9. timetuple()
Like we saw earlier, this returns a time tuple of the object.
>>> d.timetuple()
Output
10. utctimetuple()
This returns a time tuple of the UTC time.
>>> d.utctimetuple()
Output
11. timestamp()
This returns the timestamp of the object (in seconds).
>>> d.timestamp()
Output
12. weekday()
This returns the number of weekday for the object, where 0 is for Monday.
>>> d.weekday()
Output
#A Sunday
13. isoweekday()
This returns the day of the week, but with Monday as 1.
>>> d.isoweekday()
Output
14. isocalendar()
This returns a tuple of the following- ISO year, ISO week number, ISO weekday.
>>> d.isocalendar()
Output
15. isoformat()
This returns the date and time in the ISO format.
>>> d.isoformat()
Output
16. __str__()
This returns the date and time in a string representation.
>>> d.__str__()
Output
>>> str(d)
Output
17. ctime()
This, like str, returns the datetime as a string.
>>> d.ctime()
Output
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
>>> d<d1
Output
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
2. max
This one returns the most positive timedelta object.
>>> datetime.timedelta.max
Output
3. resolution
resolution returns the smallest possible difference between non-equal timedelta objects.
>>> datetime.timedelta.resolution
Output
timedelta also supports one instance method:
1. total_seconds()
This returns the total number of seconds in the duration.
>>> td.total_seconds()
Output
You can perform arithmetic operations on timedelta objects.
>>> td=datetime.timedelta(0,333) >>> td1=td*2 >>> td1
Output
So, this was all about the Python Datetime Module Tutorial. Hope you like our explanation.
Python Interview Questions on Datetime Module
- What is datetime module in Python?
- What is datetime datetime now() in Python?
- How to print the date and time in Python?
- How do you compare two times in Python?
- 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.
If you are Happy with DataFlair, do not forget to make us happy with your positive feedback on Google
i don’t understand this example
>>> d=datetime.date(2020,1,21)
>>> td=datetime.timedelta(0,99999)
>>> d1=d+td
>>> d1
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)