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

当前日期时间

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

  • 63
    点赞
  • 245
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 21
    评论
评论 21
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小龙在山东

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值