In Python language, the date and time are not the data type o their own but the datatime module provided by python can be imported to work with the 'date' and 'time'. The Datetime module is directly build into Python hence there would be no need to install it externally.
Datetime module in python supplies classes to work with date and time. These python classes provide a number of functions to deal with dates, times and time intervals. Date and datetime are an object in Python, so when you manipulate them, you are actually manipulating objects and not string or timestamps.
The datetime classes are categorized into 6 main classes –
# Python program to # demonstrate date class # import the date class from datetime import date # initializing constructor # and passing arguments in the # format year, month, date my_date = date(1996, 12, 11) print("Date passed as argument is", my_date) # Uncommenting my_date = date(1996, 12, 39) # will raise an ValueError as it is # outside range # uncommenting my_date = date('1996', 12, 11) # will raise a TypeError as a string is # passed instead of interger
Date passed as argument is 1996-12-11
To return the current local date today() function of date class is used. today() function comes with several attributes (year, month and day). These can be printed individually.
# Python program to # print current date from datetime import date # calling the today # function of date class today = date.today() print("Today's date is", today) # Printing date's components print("Date components", today.year, today.month, today.day)
Today's date is 2020-05-07 Date components 2020 5 7
Time object represents local time, independent of any day. Constructor Syntax:
class datetime.time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)
0 <= hour < 24
0 <= minute < 60
0 <= second < 60
0 <= microsecond < 1000000
fold in [0, 1]
import datetime datetime_object = datetime.datetime.now() print(datetime_object)
To Understand what is inside the datetime module we will be making use of dir() function.This function will get a list containing all attributes of a module.
import datetime print(dir(datetime))
['MAXYEAR', 'MINYEAR', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'date', 'datetime', 'datetime_CAPI', 'sys', 'time', 'timedelta', 'timezone', 'tzinfo']
You can easily instantiate date objects from the 'date' class. A 'date object' generally represents a date (year, month and day).
import datetime d = datetime.date(2019, 4, 13) print(d)
Understanding the use of 'date' when it is imported from the 'datetime' module
from datetime import date a = date(2019, 4, 13) print(a)
from datetime import date today = date.today() print("Current date =", today)
Current date = 2020-05-10
## Get date from a timestamp from datetime import date timestamp = date.fromtimestamp(1326244364) print("Date =", timestamp)
Date = 2012-01-11
We can get year, month, day, day of the week etc. from the date object easily. Here's how:
from datetime import date # date object of today's date today = date.today() print("Current year:", today.year) print("Current month:", today.month) print("Current day:", today.day)
Current year: 2020 Current month: 5 Current day: 10
A time object instantiated from the time class represents the local time.
from datetime import time # time(hour = 0, minute = 0, second = 0) a = time() print("a =", a) # time(hour, minute and second) b = time(11, 34, 56) print("b =", b) # time(hour, minute and second) c = time(hour = 11, minute = 34, second = 56) print("c =", c) # time(hour, minute, second, microsecond) d = time(11, 34, 56, 234566) print("d =", d)
a = 00:00:00 b = 11:34:56 c = 11:34:56 d = 11:34:56.234566
from datetime import time a = time(11, 34, 56) print("hour =", a.hour) print("minute =", a.minute) print("second =", a.second) print("microsecond =", a.microsecond)
hour = 11 minute = 34 second = 56 microsecond = 0
The datetime module has a class named dateclass that can contain information from both date and time objects.
from datetime import datetime #datetime(year, month, day) a = datetime(2018, 11, 28) print(a) # datetime(year, month, day, hour, minute, second, microsecond) b = datetime(2017, 11, 28, 23, 55, 59, 342380) print(b)
2018-11-28 00:00:00 2017-11-28 23:55:59.342380
from datetime import datetime a = datetime(2017, 11, 28, 23, 55, 59, 342380) print("year =", a.year) print("month =", a.month) print("hour =", a.hour) print("minute =", a.minute) print("timestamp =", a.timestamp())
year = 2017 month = 11 hour = 23 minute = 55 timestamp = 1511893559.34238
A timedelta object represents the difference between two dates or times.
from datetime import datetime, date t1 = date(year = 2018, month = 7, day = 12) t2 = date(year = 2017, month = 12, day = 23) t3 = t1 - t2 print("t3 =", t3) t4 = datetime(year = 2018, month = 7, day = 12, hour = 7, minute = 9, second = 33) t5 = datetime(year = 2019, month = 6, day = 10, hour = 5, minute = 55, second = 13) t6 = t4 - t5 print("t6 =", t6) print("type of t3 =", type(t3)) print("type of t6 =", type(t6))
t3 = 201 days, 0:00:00 t6 = -333 days, 1:14:20 type of t3 = <class 'datetime.timedelta'> type of t6 = <class 'datetime.timedelta'>
from datetime import timedelta t1 = timedelta(weeks = 2, days = 5, hours = 1, seconds = 33) t2 = timedelta(days = 4, hours = 11, minutes = 4, seconds = 54) t3 = t1 - t2 print("t3 =", t3)
t3 = 14 days, 13:55:39
from datetime import timedelta t = timedelta(days = 5, hours = 1, seconds = 33, microseconds = 233423) print("total seconds =", t.total_seconds())
total seconds = 435633.233423
The way date and time is represented may be different in different places, organizations etc. It's more common to use mm/dd/yyyy in the US, whereas dd/mm/yyyy is more common in the UK.
Python has strftime() and strptime() methods to handle this.
from datetime import datetime # current date and time now = datetime.now() t = now.strftime("%H:%M:%S") print("time:", t) s1 = now.strftime("%m/%d/%Y, %H:%M:%S") # mm/dd/YY H:M:S format print("s1:", s1) s2 = now.strftime("%d/%m/%Y, %H:%M:%S") # dd/mm/YY H:M:S format print("s2:", s2)
time: 15:54:33 s1: 05/10/2020, 15:54:33 s2: 10/05/2020, 15:54:33
If you are more comfortable learning through video tutorials then we would recommend that you subscribe to our YouTube channel.
When going through coding examples, it's quite common to have doubts and errors.
If you have doubts about some code examples or are stuck somewhere when trying our code, send us an email at firstname.lastname@example.org. We'll help you or point you in the direction where you can find a solution to your problem.
You can even send us a mail if you are trying something new and need guidance regarding coding. We'll try to respond as soon as possible.
If you want to