Use of Python's date and datetime module

Use of Python's date and datetime module

Python includes the datetime module, which provides very powerful functions to handle dates and times.

In the datetime module, commonly used objects and functions include today, year, month, day, timedelta, strftime and strptime.

Here is a demonstration of date and datetime in datetime:

#首先导入模块
from datetime import time,date,datetime,timedelta

today = date.today()

print(today)
#输出日期 今天是2020-10-20 则输出2020-10-20
print(today.year)
#输出年份 今年是2020年 则输出2020
print(today.month)
#输出月份 这个月是10月 则输出10
print(today.day)
#输出今天是几号 今天是20号 则输出20

current_datetime = datetime.today()
print(current_datetime)
#输出现在的时间 现在是2020-10-20 10:44:08.859857 则输出2020-10-20 10:44:08.859857

Let’s show you the timedelta in datetime:

#首先导入模块
from datetime import time,date,datetime,timedelta

a = timedelta(days=-1)
y_day = today +a
print(y_day)
#使用timedelta从今天减去了一天
#输出y_day,结果是2020-10-19,昨天是2020-10-20,则今天是2020-10-19

we = timedelta(week=-1)
aa1 = we+today
print(aa1)
#使用timedelta从今天减去了一周
#输出aa1,结果是2020-10-13

Let’s show you how to subtract one date from another date in datetime:

#首先导入模块
from datetime import time,date,datetime,timedelta

a = today-y_day
print(a)
#所得的a是以天、小时、分钟和秒来显示
#在这里 显示的是1 day, 0:00:00
#有时候我们只想要取这个结果的天数,用split()方法
print(str(a).split()[0])
#结果为1

Here is a demonstration of how to use formats to create date strings in different formats in datetime:

#首先导入模块
from datetime import time,date,datetime,timedelta

print(today.strftime("%m %B %Y %b %d"))
#输出的是10 October 2020 Oct 20  分别表示月份 月份(英文) 年份 月份(简写英文) 日期

The above, I hope to help you, and I think it is helpful to you, I can support you, thank you.
Your encouragement is my motivation for continuous improvement~

Guess you like

Origin blog.csdn.net/m0_50481455/article/details/109176396