As part of our application, we often need to deal with dates. Let us get an overview about dealing with dates in Python.
-
datetime
is the main library to deal with dates. -
datetime.datetime
anddatetime.date
are the classes as part ofdatetime
library that can be used to deal with dates. -
datetime.datetime
is primarily used for date with timestamp anddatetime.date
can be used for date without timestamp. -
When we try to print the date it will print as below (for
datetime
). It is due to the implementation of string representation functions such as__str__
or__repr__
.
datetime.datetime(2020, 10, 7, 21, 9, 1, 39414)
-
We need to format the date using format string to display the date the way we want. These are typically used along with functions such as
strptime
andstrftime
.%Y
- 4 digit year%m
- 2 digit month%d
- 2 digit day within month
-
Also,
datetime
library provides functions such asstrptime
to convert strings to date objects. -
Other important modules to manipulate dates.
calendar
- to get the calendar-related information for dates such as day name, month name, etc.datetime.timedelta
- to perform date arithmetic
Key Concepts Explanation
Importing datetime
To handle date and time in Python, we import the datetime
module using the alias dt
.
import datetime as dt
Getting Current Date with Timestamp
To get the current date with a timestamp, we use the now()
function from the datetime
module.
dt.datetime.now()
Getting Current Date Without Timestamp
To get the current date without a timestamp, we import the date
class and use the today()
function.
from datetime import date
date.today()
Hands-On Tasks
- Check the current date and time using the given code snippets.
- Format the current date in different ways using the
strftime
function.
Conclusion
In this article, we covered the basics of date manipulation in Python using the datetime
module. By following the hands-on tasks, you can practice working with dates and timestamps. Remember to explore further concepts and engage with the community for continuous learning.