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.
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
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, 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
>>> 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 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
3. fromtimestamp(timestamp) method in python
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 in Python
It returns the earliest representable date.
>>> datetime.date.min
Output
2. date.max in Python
Like min, max returns the latest representable date.
>>> datetime.date.max
Output
3. date.resolution in Python
resolution returns the smallest possible difference between non-equal date objects.
>>> datetime.date.resolution
Output
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
2. month attribute in Python
month returns the month from a date object.
>>> d.month
Output
3. day attribute in Python
This returns the day from a date object.
>>> d.day
Output
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
2. timetuple() method in python
timetuple() returns a tuple of attributes for the current local time.
>>> d.timetuple()
Output
3. weekday() method in python
weekday() will return the day of the week, where 0 denotes Monday.
>>> d.weekday()
Output
4. isoweekday() method in python
Here, Monday is 1.
>>> d.isoweekday()
Output
5. isocalendar() method in python
This method returns a tuple of three things- ISO year, ISO week number, and ISO weekday.
>>> d.isocalendar()
Output
6. isoformat() method in python
This returns the date in the ISO format.
>>> d.isoformat()
Output
7. __str__() method in python
This will return the current local date as a string.
>>> d.__str__()
Output
>>> str(d)
Output
8. ctime() method in python
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 attribute in Python time
This returns the earliest representable time.
>>> t.min
Output
2. max attribute in Python time
This returns the latest representable time.
>>> t.max
Output
3. resolution attribute in Python time
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 attribute in Python time
This tells us the hour from the object.
>>> t.hour
Output
2. minute attribute in Python time
This returns the minute.
>>> t.minute
Output
3. second attribute in Python time
This returns the second.
>>> t.second
Output
4. microsecond attribute in Python time
This returns the microsecond.
>>> t.microsecond
Output
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
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
3. __str__() method in python
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 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
2. now() method in python datetime
now() returns the current local date and time, but is more precise than today().
>>> datetime.datetime.now()
Output
3. utcnow() method in python datetime
utcnow() returns the current UTC time.
>>> datetime.datetime.utcnow()
Output
4. fromtimestamp() method in python datetime
This returns the date and time for the provided timestamp.
>>> datetime.datetime.fromtimestamp(time.time())
Output
5. utctimestamp() method in python datetime
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 attribute in Python datetime
Like for everything else, this returns the earliest representable datetime.
>>> datetime.datetime.min
Output
2. max attribute in Python datetime
max returns the latest representable datetime.
>>> datetime.datetime.max
Output
3. resolution attribute in Python datetime
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 attribute in Python datetime
This returns the year.
>>> d.year
Output
2. month attribute in Python datetime
This returns the month.
>>> d.month
Output
3. day attribute in Python datetime
This returns the day.
>>> d.day
Output
4. hour attribute in Python datetime
This returns the hour.
>>> d.hour
Output
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
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
2. date() method in python datetime
date() returns a date object from the datetime object.
>>> d.date()
Output
3. time() method in python datetime
time() returns a time object from the datetime object.
>>> d.time()
Output
4. timetz() method in python datetime
Other than what time() does, timetz() also returns the tzinfo value.
>>> d.timetz()
Output
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
6. utcoffset() method in python datetime
If there is a UTC offset, it returns that, else, None.
>>> print(d.utcoffset())
Output
7. dst() method in python datetime
If Daylight Savings Time applies, it returns its magnitude.
>>> print(d.dst())
Output
8. tzname() method in python datetime
If you had set tzinfo, this would return its name.
>>> print(d.tzname())
Output
9. timetuple() method in python datetime
Like we saw earlier, this returns a time tuple of the object.
>>> d.timetuple()
Output
10. utctimetuple() method in python datetime
This returns a time tuple of the UTC time.
>>> d.utctimetuple()
Output
11. timestamp() method in python datetime
This returns the timestamp of the object (in seconds).
>>> d.timestamp()
Output
12. weekday() method in python datetime
This returns the number of weekdays for the object, where 0 is for Monday.
>>> d.weekday()
Output
#A Sunday
13. isoweekday() method in python datetime
This returns the day of the week, but with Monday as 1.
>>> d.isoweekday()
Output
14. isocalendar() method in Python datetime
This returns a tuple of the following: ISO year, ISO week number, ISO weekday.
>>> d.isocalendar()
Output
15. isoformat() method in Python datetime
This returns the date and time in the ISO format.
>>> d.isoformat()
Output
16. __str__() method in python datetime
This returns the date and time in a string representation.
>>> d.__str__()
Output
>>> str(d)
Output
17. ctime() method in Python datetime
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 attribute in timedelta
This returns the most negative timedelta object.
>>> datetime.timedelta.min
Output
2. max attribute in timedelta
This one returns the most positive timedelta object.
>>> datetime.timedelta.max
Output
3. resolution attribute in timedelta
resolution returns the smallest possible difference between non-equal timedelta objects.
>>> datetime.timedelta.resolution
Output
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
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 the Datetime Module
- What is the 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 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.