In Python, we can work with dates, time, and calendars using the datetime, time and calendar modules Python provides.
In real-time applications(such as chat applications, video conference apps, and e-commerce applications) date and time are one of the most crucial parts of the applications.
The "datetime" class provides us with a specific date and time, including the year, month, day, hour, minute, second, and microsecond.
Here's a overview of "datetime" module:
import datetime # Created a datetime object for current date and time currentDatetime = datetime.datetime.now() print(currentDatetime) # Output: e.g., 2023-06-12 11:20:00.334202
The date class from datetime module represents a date without time information. The date class helps us to retrieve the Current Date.
import datetime # Creating a date object currentDate = datetime.date.today() print("Today Date:", currentDate) # Output: Today Date: 2023-06-12
This will output the current date in the format YYYY-MM-DD.
The time class from datetime module represents the time of day, independent of a specific date.
import datetime # Creating a time object currentTimeWithoutDate = datetime.time(hour=13, minute=45, second=55) print(currentTimeWithoutDate) # Output: 13:45:55
The timedelta class from datetime module represents a duration difference between two dates or times.
import datetime # Creating timedelta objects timeDelta1 = datetime.timedelta(days=3) timeDelta2 = datetime.timedelta(days=4, hours=5) # Calculating the difference between two dates date1 = datetime.date(2023, 6, 13) date2 = datetime.date(2023, 6, 19) deltaDays = date2 - date1 print(timeDelta1) # Output: 3 days, 0:00:00 print(timeDelta2) # Output: 4 days, 5:00:00 print(deltaDays) # Output: 6 days, 0:00:00
date class from datetime module helps in formatting dates.
import datetime # Creating a date object current_date = datetime.date.today() formatted_date = current_date.strftime("%Y-%m-%d") print(formatted_date) # Output: 2023-06-12
datetime module class date helps to create a specific date
import datetime specific_date = datetime.date(2022, 12, 12) print(specific_date) # Output: 2022-12-12
Formatting time using asctime function provided in the time module in Python.
# we can use time module from python for time related tasks. import time # it returns the formatted time print(time.asctime(time.localtime(time.time()))) # 0utput: Mon Jun 12 10:06:09 2023
we can use the calendar module from python to retrieve calendar info.
import calendar; specificMonth = calendar.month(2023,6) #print the calendar month of June 2023 print(specificMonth)
June 2023 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30