This article entitle Python Date Time is a continuation of the previous article entitled Python Dictionary.
Python DateTime is a module that can be used on working with dates and times. This module provides different classes for the representation and manipulation of dates and times and for parsing and formatting dates and times into different formats.
How to get date time in Python?
The DateTime module can be used to get the current date and time in Python and with the use of datetime.now() function for creating a DateTime object that contains the current DateTime.
import datetime # get the current date and time datetimenow = datetime.datetime.now() print(datetimenow)
How to get the current Date in Python?
To get the current date we have to use the method name today() which is defined on the date class to get the dates object that contains the local current date.
import datetime # get current date currentDate = datetime.date.today() print(currentDate)
How to get all the attributes of datetime module?
To get the list of all attributes of datetime module we can use the dir() function.
import datetime print(dir(datetime))
['MAXYEAR', 'MINYEAR', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'date', 'datetime', 'datetime_CAPI', 'sys', 'time', 'timedelta', 'timezone', 'tzinfo']
The following lists are the most commonly used classes of the datetime module.
- datetime.time – This function represents the date (year, month, and day) without the time.
- datetime.time – This function represents the time (hour, minute, second, and microsecond) without the date.
- datetime.datetime – This function represents a single point in time, which also includes the date and time.
- datetime.timedelta – This function represents the duration that can be used to perform arithmetic with datetime objects.
datetime.date class in Python
We can get the date objects from a date class in Python and the date objects will represent the date (year, month, and day).
Date object to represent a date in Python
The date() is the constructor of the local date class and these constructors get the three arguments such as the year, month, and day.
import datetime date = datetime.date(2022, 12, 28) print(date)
Import only the date class in Python
In Python, we can import only a date class from the module name datetime.
from datetime import date date = date(2022, 12, 28) print(date)
How to get the current date using today() function in Python
The today() method is most commonly used to get the current date and print today.
from datetime import date # today() to get current date todaysDate = date.today() print("Date today =", todaysDate)
Date today = 2022-12-28
How to get the date from a timestamp in Python
The timestamp is also used to create date objects, further, a UNIX timestamp is a number of seconds that is between the particular date and January 1, 1970, at UTC and you can convert the timestamp to the date with the use of the method named fromtimestamp().
from datetime import date timestamp = date.fromtimestamp(1326244364) print("Date =", timestamp)
Date = 2012-01-11
How to print the current year, month, and day in Python
To get the current year, month, and day from the given date object can be done simply.
from datetime import date # date object of today's date today = date.today() print("The current year is", today.year) print("The current month is", today.month) print("The current day is", today.day)
The current year is 2022 The current month is 12 The current day is 28
datetime.time class in Python
The time object is instantiated from a time module class that represents the local time zone.
Object time to represent a time
from datetime import time # time(hour = 0, minute = 0, second = 0) timeA = time() print(timeA) # time(hour, minute and second) timeB = time(12, 24, 16) print(timeB) # time(hour, minute and second) timeC = time(hour = 10, minute = 45, second = 16) print(timeC) # time(hour, minute, second, microsecond) timeD = time(10, 45, 16, 234566) print(timeD)
00:00:00 12:24:16 10:45:16 10:45:16.234566
Display hour, minute, second, and microsecond
For instance, if we want to create a time object we can easily display all the attributes such as an hour, minute, and second.
from datetime import time t = time(10, 23, 43) print("Hour =", t.hour) print("Minute =", t.minute) print("Second =", t.second) print("Microsecond =", t.microsecond)
Hour = 10 Minute = 23 Second = 43 Microsecond = 0
datetime.datetime class in Python
The datetime module has also a class named datetime which contains all the information about the object’s date and time interval.
datetime object in Python
The following program takes the first three arguments year, month, and day in the function datetime() and the constructor is mandatory.
from datetime import datetime # datetime(year, month, day) timeA = datetime(2022, 12, 28) print(timeA) # datetime(year, month, day, hour, minute, second, microsecond) timeB = datetime(2022, 12, 28, 23, 55, 59, 342380) print(timeB)
2022-12-28 00:00:00 2022-12-28 23:55:59.342380
Display year, month, hour, minute, and timestamp
from datetime import datetime dateTime = datetime(2022, 12, 28, 12, 30, 59, 342380) print("Year =", dateTime.year) print("Month =", dateTime.month) print("Hour =", dateTime.hour) print("Minute =", dateTime.minute) print("Timestamp =", dateTime.timestamp())
Year = 2022 Month = 12 Hour = 12 Minute = 30 Timestamp = 1672230659.34238
datetime.timedelta class in Python
A timedelta is an object that represents the difference between the two dates and times.
from datetime import datetime, date # using date() time1 = date(year = 2022, month = 12, day = 28) time2 = date(year = 2021, month = 10, day = 15) time3 = time1 - time2 print("time3 =", time3) # using datetime() time4 = datetime(year = 2022, month = 12, day = 28, hour = 8, minute = 19, second = 24) time5 = datetime(year = 2021, month = 3, day = 7, hour = 4, minute = 34, second = 23) time6 = time4 - time5 print("time6 =", time6) print("Type of time3 =", type(time3)) print("Type of time6 =", type(time6))
time3 = 439 days, 0:00:00 time6 = 661 days, 3:45:01 Type of time3 = <class 'datetime.timedelta'> Type of time6 = <class 'datetime.timedelta'>
Difference between two timedelta objects in Python
from datetime import timedelta time1 = timedelta(weeks = 3, days = 6, hours = 2, seconds = 22) time2 = timedelta(days = 2, hours = 5, minutes = 3, seconds = 34) time3 = time1 - time2 print("time3 =", time3)
time3 = 24 days, 20:56:48
Time duration in seconds in Python
The total_seconds() is a method that can get the total number of seconds in the object timedelta.
from datetime import timedelta time = timedelta(days = 6, hours = 3, seconds = 22, microseconds = 434343) print("Total seconds =", time.total_seconds())
Total seconds = 529222.434343
Format datetime in Python
The date and time are a way that is represented in different places, organizations, and so on. The most common use date and time format is mm/dd/yyyy in the United States while in the United Kingdom is dd/mm/yyyy.
strftime() method in Python
The strftime() is a method that is defined under the class date, time, and datetime. This method creates a string formatted from the date given object datetime or time.
from datetime import datetime # current date and time now = datetime.now() time = now.strftime("%H:%M:%S") print("Time:", time) strf1 = now.strftime("%m/%d/%Y, %H:%M:%S") # mm/dd/YY H:M:S format print("String Format One:", strf1) strf2 = now.strftime("%d/%m/%Y, %H:%M:%S") # dd/mm/YY H:M:S format print("String Format Two:", strf2)
Time: 06:44:27 String Format One: 12/28/2022, 06:44:27 String Format Two: 28/12/2022, 06:44:27
strptime() method in Python
The strptime() is a method that can be used to create an object datetime from a string given that represents date and time.
from datetime import datetime stringDate = "28 December, 2022" print("stringDate =", stringDate) # use strptime() to create date object objectDate = datetime.strptime(stringDate, "%d %B, %Y") print("objectDate =", objectDate)
stringDate = 28 December, 2022 objectDate = 2022-12-28 00:00:00
Python handling timezone
For instance that we are working on a project and we need to display the date and time that is based on their timezone.
from datetime import datetime import pytz local = datetime.now() print("Local:", local.strftime("%m/%d/%Y, %H:%M:%S")) us = pytz.timezone('America/New_York') datetimeUs = datetime.now(us) print("New York:", datetimeUs.strftime("%m/%d/%Y, %H:%M:%S")) uk = pytz.timezone('Europe/London') datetimeUk = datetime.now(uk) print("London:", datetimeUk.strftime("%m/%d/%Y, %H:%M:%S"))
Local: 12/28/2022, 06:58:39 New York: 12/28/2022, 01:58:39 London: 12/28/2022, 06:58:39
In summary, you have read about Python Date Time. We also discussed in this article how to get date time in Python, how to get the current date, how to get all the attributes of datetime module, datetime.date class.
Along with is datetime object, display year, month, hour, minute, and timestamp, datetime.timedelta class, difference between two timedelta objects, time duration in seconds, and handling timezone.
I hope this article could help you a lot to continue pursuing learning this powerful programming language.
If you want to learn more check out my previous and latest articles for more career-changing articles.