Python 日期时间datetime 加一天,减一天,加减一小时一分钟,加减一年一月,时区转换、月初月末

您所在的位置:网站首页 python将文件名中加入日期 Python 日期时间datetime 加一天,减一天,加减一小时一分钟,加减一年一月,时区转换、月初月末

Python 日期时间datetime 加一天,减一天,加减一小时一分钟,加减一年一月,时区转换、月初月末

2024-07-01 20:59| 来源: 网络整理| 查看: 265

当前日期时间 import datetime print(datetime.datetime.now()) # 2018-05-08 16:53:30.101000 格式化时间 import datetime print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")) # 2018-05-08 16:54 多加一天 import datetime print((datetime.datetime.now()+datetime.timedelta(days=1)).strftime("%Y-%m-%d %H:%M:%S")) # 2018-05-09 16:56:07 减一天 import datetime print((datetime.datetime.now()+datetime.timedelta(days=-1)).strftime("%Y-%m-%d %H:%M:%S")) # 2018-05-07 16:56:59

其他类似

import datetime in_date = '2016-08-31' dt = datetime.datetime.strptime(in_date, "%Y-%m-%d") out_date = (dt + datetime.timedelta(days=2)).strftime("%Y-%m-%d") print(out_date) # 2016-09-02

可以把days改为hours minutes,就可以提前XX小时/分钟了。

timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])

减去一年 import datetime from dateutil.relativedelta import relativedelta d = datetime.datetime.strptime('20180131', '%Y%m%d') print(d) // 2018-01-31 00:00:00 print((d - relativedelta(years=1)).strftime('%Y%m%d')) // 20170131

还可以把years改为months

时区转换 from datetime import datetime from datetime import timezone from datetime import timedelta # 世界标准时间 utc_time = datetime(2019, 7, 30, 7, 50, 0) # 北京时间UTC+8 cst_time =utc_time.astimezone(timezone(timedelta(hours=-8))).strftime("%Y-%m-%d %H:%M:%S") 月初月末 from datetime import datetime, timedelta today = datetime.today() first_day_of_this_month = today.replace(day=1) last_day_of_last_month = first_day_of_this_month - timedelta(days=1) first_day_of_last_month = last_day_of_last_month.replace(day=1) first_day_of_last_month_formart = first_day_of_last_month.strftime('%Y-%m-%d 00:00:00') last_day_of_last_month_formart = last_day_of_last_month.strftime('%Y-%m-%d 23:59:59') print(first_day_of_last_month_formart) print(last_day_of_last_month_formart) 参考:

https://docs.python.org/2/library/datetime.html#timedelta-objects https://dateutil.readthedocs.io/en/stable/index.html



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3