In Python, the datetime module provides classes for manipulating dates and times. Depending on whether or not timezone information is included, the date and time objects can be classified as “aware” or “naive.”
An aware object denotes a precise point in time that cannot be interpreted in any way. A naïve object lacks sufficient information to situate itself unambiguously in relation to other date/time objects.
Python datetime module:
Let’s use the datetime module to manipulate date and time. The datetime modules come with python installation, so you do not need to install them explicitly.
To use it, you need to import the corresponding classes or methods from the datetime module on your code like below.
Let’s look at the types and functions by introspecting the datetime module. As discussed in the earlier articles dir()
is one of the python introspection functions.
Run:
import datetime
print(dir(datetime))
Output:
['MAXYEAR', 'MINYEAR', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'date', 'datetime', 'datetime_CAPI', 'sys', 'time', 'timedelta', 'timezone', 'tzinfo']
We can see the different attributes and functions in the datetime module in the above output. Among all of them, we will discuss the date, datetime, time, timedelta, timezone and tzinfo
here.
- date: The Date class with year, month and day. It works based on the current Gregorian calendar.
- datetime: A date and time combination. Individual classes have their attributes and criteria.
- time: Hour, minute, second, and microsecond are properties of idealized time. The requirement is that each day has precisely 24 * 60 * 60 seconds in it. Because there is no leap second, it is idealized.
- timedelta: Determines the amount of time passed between two points in time.
- timezone: UTC and time zones. It makes use of the abstract base class
tzinfo
. - tzinfo: Time zone information objects have an abstract base class. Datetime and time classes utilize them to give a customized concept of time adjustment.
Now let’s see what datetime class offers by importing all:
from datetime import *
print(dir(datetime))
Output:
['__add__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__radd__', '__reduce__', '__reduce_ex__', '__repr__', '__rsub__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', 'astimezone', 'combine', 'ctime', 'date', 'day', 'dst', 'fold', 'fromisocalendar', 'fromisoformat', 'fromordinal', 'fromtimestamp', 'hour', 'isocalendar', 'isoformat', 'isoweekday', 'max', 'microsecond', 'min', 'minute', 'month', 'now', 'replace', 'resolution', 'second', 'strftime', 'strptime', 'time', 'timestamp', 'timetuple', 'timetz', 'today', 'toordinal', 'tzinfo', 'tzname', 'utcfromtimestamp', 'utcnow', 'utcoffset', 'utctimetuple', 'weekday', 'year']
We can observe how well it will work from the above output if we import the needed parts.
Let’s only import date from the datetime module:
from datetime import date
print(dir(date))
Output:
['__add__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__radd__', '__reduce__', '__reduce_ex__', '__repr__', '__rsub__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', 'ctime', 'day', 'fromisocalendar', 'fromisoformat', 'fromordinal', 'fromtimestamp', 'isocalendar', 'isoformat', 'isoweekday', 'max', 'min', 'month', 'replace', 'resolution', 'strftime', 'timetuple', 'today', 'toordinal', 'weekday', 'year']
We can see more filtered output than previous.
Now let’s see some of the use cases of using the datetime module.
Get current date:
Python datetime module has a today() function that will return today’s date. Let’s try that:
from datetime import date
today = date.today()
print(today)
Output:
2021-11-25
Formatting the date:
If the date needs to be printed as per your needs, strftime()
can be used to make the necessary changes.
We use the method strftime (“STRingFromTIME”) to convert the datetime object to a string for output. We may additionally select the data from the date we wish to print (e.g., day, year, etc.).
Run:
from datetime import datetime
formatdate = datetime.now()
print(formatdate.strftime("%d.%m.%Y"))
Output:
25.11.2021
Get weekday as a number:
weekday()
function returns the number of days of the week on a given date. By default, the week starts from Monday. For example, Monday is a zero, Tuesday is a one, etc.
Let’s find what day is today:
from datetime import date
today = date.today()
print(today.weekday())
Output:
3
If Monday is 0 then, 3 is Thursday.
Get the day of the week:
Now output the day of the week as text using a list:
from datetime import date
today = date.today()
tweekday = today.weekday()
print(tweekday)
days= ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
print("Today is: ", days[tweekday])
Output:
3
Today is: Thursday
In the above program, we assume that Monday is the first day of the week. If your week starts from Sunday, use isoweekday()
instead of weekday()
.
Replace something in the date:
If you need to replace something on an existing date, we can do that with replace()
function.
Let’s pretend if we want to know the day of the week and the calendar week for Christmas this year and next year.
from datetime import date
date = date(2021, 12, 25)
print(date.isocalendar())
newdate = date.replace(year=2022)
print(newdate.isocalendar())
Output:
datetime.IsoCalendarDate(year=2021, week=51, weekday=6)
datetime.IsoCalendarDate(year=2022, week=51, weekday=7)
We can predict that next Christmas is on week 51, on Sunday from the output.
isocalendar()
provides a tuple with the information in chronological order (year, calendar week, weekday in ISO format).
Get date from timestamp:
A Unix timestamp is the number of seconds elapsed between a specific date and at UTC on January 1, 1970. The fromtimestamp()
function is used to convert a timestamp to date. It takes UNIX timestamp as an argument.
from datetime import date
timestamp = date.fromtimestamp(1426244394)
print("Date:", timestamp)
Output:
Date: 2015-03-13
Get today’s year month and day separately:
To read year, date and month individually? Here is the solution.
from datetime import date
tdate = date.today()
print("Year:", tdate.year)
print("Month:", tdate.month)
print("Day:", tdate.day)
Output:
Year: 2021
Month: 12
Day: 1
Get the time from datetime:
We convert our text to a DateTime object and then use the .time()
function to get the time from our DateTime object.
from datetime import datetime
dts = "01DEC2021020510"
dts_obj = datetime.strptime(dts, "%d%b%Y%H%M%S")
time = dts_obj.time()
print(time)
Output:
02:05:10
strptime() function:
The strftime()
function is defined in the date, datetime, and time classes. From a specified date, datetime, or time object, the method generates a formatted string.strftime()
accepts one or more format codes and produces a formatted string depending on them. We used mm/dd/YY H:M:S
format for strp1
and dd/mm/YY H:M:S
format for strp2
.
from datetime import datetime
cur= datetime.now()
t = cur.strftime("%H:%M:%S")
print("time:", t)
strp1 = cur.strftime("%m/%d/%Y, %H:%M:%S")
print("strptime 1:", strp1)
strp2 = cur.strftime("%d/%m/%Y, %H:%M:%S")
print("strptime 2:", strp2)
Output:
time: 05:15:21
strptime 1: 12/01/2021, 05:15:21
strptime 2: 01/12/2021, 05:15:21
Two different timezones:
To handle timezones, we need to install pytz
module:
easy_install --upgrade pytz
Output:
Searching for pytz
Reading https://pypi.org/simple/pytz/
Downloading https://files.pythonhosted.org/packages/d3/e3/d9f046b5d1c94a3aeab15f1f867aa414f8ee9d196fae6865f1d6a0ee1a0b/pytz-2021.3-py2.py3-none-any.whl#sha256=3672058bc3453457b622aab7a1c3bfd5ab0bdae451512f6cf25f64ed37f5b87c
Best match: pytz 2021.3
Processing pytz-2021.3-py2.py3-none-any.whl
Installing pytz-2021.3-py2.py3-none-any.whl to /home/nilesh/anaconda3/lib/python3.8/site-packages
Adding pytz 2021.3 to easy-install.pth file
Installed /user/anaconda3/lib/python3.8/site-packages/pytz-2021.3-py3.8.egg
Processing dependencies for pytz
Finished processing dependencies for pytz
We need to import pytz
into our program to use it. Let us also assign current date and time from London to dtL
.
from datetime import datetime
import pytz
cur = datetime.now()
print("Current date and time in your timezone:", cur.strftime("%m/%d/%Y, %H:%M:%S"))
tzL = pytz.timezone('Europe/London')
dtL = datetime.now(tzL)
print("Current date and time in London", dtL.strftime("%m/%d/%Y, %H:%M:%S"))
Output:
Current date and time in your timezone: 12/01/2021, 05:26:22
Current date and time in London 12/01/2021, 11:26:22
Timedelta:
Now, let’s learn about timedelata
. The difference between two dates or times is represented as a timedelta
object.
Let’s find the difference between the two dates and times.
from datetime import timedelta
time1 = timedelta(weeks = 4, days = 10, hours = 6, seconds = 13)
time2 = timedelta(days = 3, hours = 12, minutes = 3, seconds = 24)
time3 = time1 - time2
print("Difference between two times =", time3)
Output:
Difference between two times = 34 days, 17:56:49
References:
Happy Learning 🙂