Little knowledge of Python: dealing with dates with datetime

Handling dates with datetime

To be honest, I've been a little busy and tired recently, and I almost want to stop. Just hold on.

Earlier we learned that the time module can be used to get the time:

>>> import time
>>> time.time()
1641946864.4970088

The time module returns the number of seconds since the early morning of January 1, 1970. Many other programming languages, such as Java, return milliseconds. Python is seconds.

If you want to process it into a specific date and time, you need to go through some calculations. Of course, we don't need to do these calculations ourselves, just use the datetime library.

It can be understood like this:

  • time is a primitive library that returns seconds. equivalent to raw materials.
  • And datetime makes raw materials into a better timepiece. The clock has the date, time, and more.

Comprehensive example

datetime also comes with Python, no need to install it. See example:

import datetime

# 第一个datetime是包名
# 第二个datetime是包中的名为datetime的对象
# now()是datetime对象的一个方法
now = datetime.datetime.now()

# 打印一下现在的时间
print(now)

# 打印年,月,日,时,分,秒,星期
print(now.year)
print(now.month)
print(now.day)
print(now.hour)
print(now.minute)
print(now.second)
print(now.weekday())

The above example comments are written more clearly, so I won't repeat them here. The print result is as follows:

2022-01-12 08:30:28.487363
2022
1
12
8
30
28
2

format

By default datetime objects are printed like this:

2022-01-12 08:30:28.487363

We can customize the output format with the strftime method as needed:

print(now.strftime("%Y年%m月%d日 %H:%m:%S"))

print result:

2022011208:01:27

The parameter of the function strftime( ) is a string, in which those **%Y**, %m , %H , etc. have specific meanings, representing the year, month, hour, etc., and other parts of the string can be freely written as needed enter.

This practice is common to basically all programming languages, here is a list of these placeholders with special meanings:

insert image description here

Recommended reading

My cousin said that this Python scheduled task can earn 5,000 yuan. Do you believe me?

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326867402&siteId=291194637