A Date With the Datetime Module in Python | Part - 1

Search for a command to run...

No comments yet. Be the first to comment.
Unlock the Power of Python Comprehensions to Enhance Your Code's Clarity and Performance

Hello, friends! Today, I want to share why you should avoid sending mere "Hi!" or "Hey!" messages when trying to communicate with your colleagues or even friends. Having worked for three years, one immediate lesson I learned is that nobody has time t...

Python. You might be thinking I know what a list is, I have used it numerous times. But there is a difference between using a list and using a list efficiently. So, I will show you what I have learned as a Software Engineer. We can create a list basi...

As developers, we face many cases when we import data from one source and want to upload this data into another source. This was the same situation I was facing. I exported data from Notion and wanted to import it into the MongoDB Atlas. To insert da...

We have explored how to get current date, month, year and day of the week in the previous blog. In this blog post we will explore more of a datetime and its corresponding methods with some tutorial. Get the Current Week Number using Python There are ...

We can extract current date using two classes.
date classfrom datetime import date
today = date.today()
datetime classfrom datetime import datetime
today = datetime.today()
OR
from datetime import datetime
now = datetime.now()
The main difference between date.today() and datetime.today() is that date class just return the date object. Whereas, datetime class returns not only date but time as well.
today = datetime.today()
print(f"Today: {today}")
print(f"Year: {today.year}")
print(f"Month: {today.month}")
print(f"Day: {today.day}")
OUTPUT:
Today: 2022-10-22 17:13:37.918735
Year: 2022
Month: 10
Day: 22
today = datetime.today()
print(f"Today: {today}")
print(f"Weekday: {today.weekday()}")
"""
OUTPUT:
Today: 2022-10-22 17:32:48.396792
Weekday: 5
"""
This weekday() method will work with both the date and datetime class.
Note: Here, weekday() method will return index between 0 to 6.
today = datetime.now()
print(f"Today: {today}")
print(f"Hour: {today.hour}")
print(f"Minute: {today.minute}")
print(f"Second: {today.second}")
OUTPUT:
Today: 2022-10-22 17:41:01.076569
Hour: 17
Minute: 41
Second: 1