Ten minutes of python entry date and time

1.Python date

Dates in Python are not their own data type, but we can import  datetime the module named to treat dates as date objects.

1.1 Import the datetime module and display the current date:

import datetime

#导入 datetime 模块并显示当前日期:
x = datetime.datetime.now()
print(x)
#输出:2023-08-03 17:03:07.766958

1.2 Return information about date objects, such as year, month, day, etc.

#年,月,日
x = datetime.datetime.now()

print(x.year, x.month, x.day)
#输出:2023 8 3

1.3 Create date object

To create a date, we can use  datetime() the class (constructor) of the datetime module.

datetime() The class requires three parameters to create a date: year, month, and day.

#创建日期对象
x = datetime.datetime(2020, 5, 17)

print(x)
#输出:2020-05-17 00:00:00

#datetime() 类还接受时间和时区(小时、分钟、秒、微秒、tzone)的参数
x = datetime.datetime(2020, 5, 17, 12, 12, 12)
print(x)
#输出:2020-05-17 12:12:12

1.4 Format date

datetime The object has methods for formatting date objects into readable strings.

The method is called  strftime()and takes a  format parameter to specify the format of the returned string:


# 格式化输出日期
d = datetime.date(2023, 5, 1)
print(d.strftime('%Y-%m-%d'))
#输出:2023-05-01

# 格式化输出时间
t = datetime.time(12, 30, 45)
print(t.strftime('%H:%M:%S'))
#输出:12:30:45

# 格式化输出datetime对象
dt = datetime.datetime(2023, 5, 1, 12, 30, 45)
print(dt.strftime('%Y-%m-%d %H:%M:%S'))
#输出:2023-05-01 12:30:45

In addition to the strftime() function, we can also use the strptime() function to convert strings into date and time objects. The parameters of the strptime() function are a string and a format string, which can parse the string into corresponding date and time objects. Here is an example code that converts a string into a date object:

# 将字符串解析成date对象
s = '2023-05-01'
d = datetime.datetime.strptime(s, '%Y-%m-%d').date()
print(d)
#输出:2023-05-01

Reference for all legal format codes: 

 1.4 Date and time operations

1.4.1 Get the date two days later
#获取两天后的日期
# 获取当前日期
today = datetime.date.today()
# 打印当前日期
print("今天是:", today)
# 获取两天后的日期
delta = datetime.timedelta(days=2)
newDate = today + delta
# 打印两天后的日期
print("两天后是:", newDate)
#输出:两天后是: 2023-08-05
1.4.2 Calculate the difference in days between two dates
# 计算两个日期之间的天数差
d1 = datetime.date(2023, 5, 1)
d2 = datetime.date(2023, 5, 10)
delta = d2 - d1
print(delta.days)
#输出:9
1.4.3 Calculate the difference in seconds between two times
# 计算两个时间之间的秒数差
t1 = datetime.time(12, 30, 45)
t2 = datetime.time(13, 30, 45)
delta = datetime.datetime.combine(datetime.date.today(), t2) - datetime.datetime.combine(datetime.date.today(), t1)
print(delta.seconds)
#输出:3600

Source code download

If this document is not detailed enough, you can refer to learn python in ten minutes_bilibili_bilibili​

Guess you like

Origin blog.csdn.net/kan_Feng/article/details/132087741