import calendar
import datetime
now = datetime.datetime.now()
print(now)
now = datetime.datetime.now().date()
print(now)
now = datetime.date.today()
print(now)
this_month_start = datetime.datetime(now.year, now.month, 1)
print(this_month_start)
this_month_end = datetime.datetime(now.year, now.month, calendar.monthrange(now.year, now.month)[1])
this_season_start = datetime.datetime(now.year, ((now.month - 1) // 3) * 3 + 1, 1)
this_season_end = datetime.datetime(now.year, ((now.month-1) // 3) * 3 + 3, calendar.monthrange(now.year, ((now.month-1) // 3) * 3 + 3)[1])
print(this_month_end)
print(this_season_start)
print(type(this_month_end))
print(this_season_end)
print(type(this_season_end))
str_this_season_end = this_season_end.strftime("%Y-%m-%d %H:%M:%S")
print(str_this_season_end)
print(type(str_this_season_end))
tmp = datetime.datetime.strptime(str_this_season_end, "%Y-%m-%d %H:%M:%S")
print(tmp)
print(type(tmp))
结果
2021-06-22 19:24:39.287237
2021-06-22
2021-06-22
2021-06-01 00:00:00
2021-06-30 00:00:00
2021-04-01 00:00:00
<class 'datetime.datetime'>
2021-06-30 00:00:00
<class 'datetime.datetime'>
2021-06-30 00:00:00
<class 'str'>
2021-06-30 00:00:00
<class 'datetime.datetime'>
这篇博客探讨了Python中如何使用`datetime`和`calendar`模块进行日期和时间的处理。作者展示了获取当前日期、月份开始和结束日期,以及季度开始和结束日期的方法。此外,还涉及到将日期时间转换为字符串以及反向解析字符串到日期时间的操作。

被折叠的 条评论
为什么被折叠?



