Last Updated on 2021-08-03 by Clay
If we want to processing date and time using Python, the datetime module that comes to minds first. The datetime
module encapsulates Python’s date-related processing very well, and I have used it a lot in crawlers.
I think the part that I can introduce is divided into three parts:
- Display date and time
- Add and subtract actions on the date
- Change the default output format
If you want to see how the Python official document explains the datetime
module, you can directly refer to the official website: https://docs.python.org/zh-cn/3/library/datetime.html
datetime module usage
Let’s first look at how to use datetime
to display the current date:
import datetime
The datetime
module is a native Python module and does not require additional download.
# Display print('All:', datetime.datetime.now()) print('Year:', datetime.datetime.now().year) print('Month:', datetime.datetime.now().month) print('Day:', datetime.datetime.now().day) print('Weekday:', datetime.datetime.now().weekday()) print('Time:', datetime.datetime.now().time())
Output:
All: 2019-11-07 19:04:57.535884
Year: 2019
Month: 11
Day: 7
Weekday: 3
Time: 19:04:57.535884
We can see from the above code that we can use datetime
to print out the current time, which contains four items: year, month, day, time. Of course, we can also print them separately, or print them on the day of the week.
Date calculation
In addition, dates can also be added and subtracted, just use datetime.timedelta()
.
print('Today:', datetime.datetime.now()) print('Yesterday:', datetime.datetime.now() - datetime.timedelta(days=1))
Output:
Today: 2019-11-07 19:04:57.535884
Yesterday: 2019-11-06 19:04:57.535884
The front is today’s date, and the back is our date minus one day. In addition to setting the number of days, we can also increase or decrease the time. (This is very useful in crawlers)
Adjust the output format
In addition, if the time format we deal with is not what we want, we can of course use regular expression to modify it. But the datetime
module in Python has already helped you encapsulate the customized output function.
# Format print('Date:', (datetime.datetime.now() - datetime.timedelta(days=1)).strftime('%Y/%m/%d'))
Output:
Date: 2019/11/06
As you can see, the output format of the current date is the same as we set, which is convenient for us to do later processing.
So the above are some tips on the datetime
module in Python.
References
- https://www.dataquest.io/blog/python-datetime-tutorial/
- https://www.programiz.com/python-programming/datetime
- https://www.w3schools.com/python/python_datetime.asp