Python来获取昨天、今天、上个月、下个月的日期

这段代码演示了如何使用Python的datetime模块获取当前时间、昨天、明天、当前日期以及未来特定时间点,如一秒后、一分钟后、一小时后和一年后。此外,还展示了如何获取上个月和下个月的开始及结束日期。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

 '获取今天(现在时间) '昨天 '明天 '获取当前日期 '一秒后的时间 '一分钟后的时间 '一小时后的时间'一年后的时间

获取上个月日期

获取下一个月开始日期和结束日期

获取上一个月开始日期和结束日期


 '获取今天(现在时间)
 '昨天
 '明天
 '获取当前日期
 '一秒后的时间
 '一分钟后的时间
 '一小时后的时间
'一年后的时间

import datetime
 
# 获取今天(现在时间)
today = datetime.datetime.today()
# 昨天
yesterday = today - datetime.timedelta(days=1)
# 明天
tomorrow = today + datetime.timedelta(days=1)
 
# 获取当前日期
date = datetime.date.today()
# 获取一秒后的时间
s = today + datetime.timedelta(seconds=1)
# 获取一分钟后的时间
m = today + datetime.timedelta(minutes=1)
# 获取一小时后的时间
h = today + datetime.timedelta(hours=1)
# 获取一年后的时间
y = today + datetime.timedelta(days=365)
 
print('获取今天(现在时间):{}\n'.format(today),
      '昨天:{}\n'.format(yesterday),
      '明天:{}\n'.format(tomorrow),
      '获取当前日期:{}\n'.format(date),
      '一秒后的时间:{}\n'.format(s),
      '一分钟后的时间:{}\n'.format(m),
      '一小时后的时间:{}\n'.format(h),
      '一年后的时间:{}'.format(y))

获取上个月日期

 >>> import datetime
 # 1. 获取「今天」
 >>> today = datetime.date.today()
 # 2. 获取当前月的第一天
 >>> first = today.replace(day=1)
 # 3. 减一天,得到上个月的最后一天
 >>> last_month = first - datetime.timedelta(days=1)
 # 4. 格式化成指定形式
 >>> print(last_month.strftime("%Y%m"))
 201807
 >>>

获取下一个月开始日期和结束日期

import time
import datetime
import calendar
from dateutil.relativedelta import relativedelta
cur_date_str = str(time.strftime("%Y-%m", time.localtime())) + "-01"
cur_date_str = datetime.datetime.strptime(cur_date_str, '%Y-%m-%d')
pastTimes1_start = cur_date_str - relativedelta(months=-1)  # 这个1指 当前月份 往前推1个月
pastTimes1_end = str(pastTimes1_start.year) + "-" + str(pastTimes1_start.month) + '-' + str(
    calendar.monthrange(int(pastTimes1_start.year), int(pastTimes1_start.month))[1])

print(pastTimes1_start)
print(pastTimes1_end)

如下 

D:\Python310\python.exe C:/Users/Administrator/Desktop/测试代码.py
2022-06-01 00:00:00
2022-6-30

Process finished with exit code 0

获取上一个月开始日期和结束日期

import time
import datetime
import calendar
from dateutil.relativedelta import relativedelta
cur_date_str = str(time.strftime("%Y-%m", time.localtime())) + "-01"
cur_date_str = datetime.datetime.strptime(cur_date_str, '%Y-%m-%d')
pastTimes1_start = cur_date_str - relativedelta(months=1)  # 这个1指 当前月份 往前推1个月
pastTimes1_end = str(pastTimes1_start.year) + "-" + str(pastTimes1_start.month) + '-' + str(
    calendar.monthrange(int(pastTimes1_start.year), int(pastTimes1_start.month))[1])

print(pastTimes1_start)
print(pastTimes1_end)

如下:

D:\Python310\python.exe C:/Users/Administrator/Desktop/测试代码.py
2022-04-01 00:00:00
2022-4-30

Process finished with exit code 0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值