In this tutorial you will learn:
Dates in Python
In Python there are classes that gives us functions to manipulate dates and time. There are certain modules that are provided by Python and in order to bring those modules into our code we need to use import statements. These modules are called classes and they are containers that contain different functions. In order to work with date and time we need to import datetime function from date class.
from datetime import date
Creating a date object with known values
import datetime print("Creating Date Object") d = datetime.date(2020,12,11) print("Created date object: ", d)
Getting the current date in Python
from datetime import date dateToday = date.today() print("Date Today: ", dateToday)
Getting current date along with current timestamp
from datetime import datetime now = datetime.now() print("Date time right now:", now)
Separately getting today's day, month and year
from datetime import date dateToday = date.today() print("Month Today:", dateToday.month) print("Day Today:", dateToday.day) print("Year Today:", dateToday.year)
Time in Python
To get time in Python we need to import time function from the date time class.
Example:
from datetime import time time = time(4, 15, 20) print("\n\nTime: ", time) print("Hour in time object: ", time.hour) print("Minutes in time object: ", time.minute) print("Seconds in time object: ", time.second)
Converting datetime object to string
In order to convert datetime object to string Python provides a function known as strftime function. It allows us to get time formatted string from a time object.
from datetime import datetime now = datetime.now() dateTime1 = now.strftime("%m/%d/%Y, %H:%M:%S") print("Date in Month/Day/Year and time in Hour: Min: Sec: ", dateTime1)
time = now.strftime("%H:%M:%S") print("Time in Hour : Minute: Second :", time)
Calendar in Python
In order to get the calendar we need to import the calendar module on our code. This module gives us all functions of a calendar.
print("\n\nCalendar in Python: ") import calendar cal = calendar.month(2020, 11) print(cal)