Menu
Python Date and Time
In Python programming, date and time can be handled with the datetime module. The four important classes of this module are namely datetime, date, time and timedelta.
We can use the now() method of datetime class to create an datetime object containing the current local date & time.
We may use the today() method of date class to create an object containing the current local date.
A time object instantiated from the time class also represents the local time.
The datetime object has a method named strftime() for formatting date objects into readable strings.
The difference between two timedelta objects is also shown here.
This the the complete code to demonstrate the datetime module:
import datetime
# date contains year, month, day, hour, minute, second, and microsecond
datetime_obj = datetime.datetime.now()
print("Current date and time:", datetime_obj)
print()
# Get current date only
date_obj = datetime.date.today()
print("Current date:", date_obj)
print()
# Get today's year, month and day
print("Current year:", date_obj.year)
print("Current month:", date_obj.month)
print("Current day:", date_obj.day)
print()
# time(hour, minute and second)
t = datetime.time(11, 35, 50)
print("t =", t)
print("hour =", t.hour)
print("minute =", t.minute)
print("second =", t.second)
print("microsecond =", t.microsecond)
print()
# Get current time only
time_obj = datetime_obj.strftime("%H:%M:%S")
print("time:", time_obj)
# mm/dd/YY H:M:S format
s1 = datetime_obj.strftime("%m/%d/%Y, %H:%M:%S")
print("s1:", s1)
# dd/mm/YY H:M:S format
s2 = datetime_obj.strftime("%d/%m/%Y, %H:%M:%S")
print("s2:", s2)
print()
t1 = datetime.timedelta(weeks = 1, days = 5, hours = 14, seconds = 42)
t2 = datetime.timedelta(days = 4, hours = 12, minutes = 5, seconds = 56)
t3 = t1 - t2
print("t3 =", t3)
Output:
Current date and time: 2019-07-13 11:47:33.979587
Current date: 2019-07-13
Current year: 2019
Current month: 7
Current day: 13
t = 11:35:50
hour = 11
minute = 35
second = 50
microsecond = 0
time: 11:47:33
s1: 07/13/2019, 11:47:33
s2: 13/07/2019, 11:47:33
t3 = 8 days, 1:54:46