python计算时间加减_python计算时间加减_python datetime库使用和时间加减计算

datetime库使用

一、操作当前时间

1.获取当前时间

>>> import datetime

>>> print datetime.datetime.now()

2019-07-11 14:24:01.954000

时间格式化输出:

>>> print datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

2019-07-11 14:25:33

>>> print datetime.datetime.now().strftime("%Y%m%d")

20190711

>>> print datetime.datetime.now().strftime("%Y-%m-%d %H:%M")

2019-07-11 14:25

使用timedelta方法对当前时间进行加减

加 一分钟

>>> print (datetime.datetime.now()+datetime.timedelta(minutes=1)).strftime("%Y-%m-%d %H:%M:%S")

2019-07-11 14:29:46

减 一分钟

>>> print (datetime.datetime.now()+datetime.timedelta(minutes=-1)).strftime("%Y-%m-%d %H:%M:%S")

2019-07-11 14:29:32

加 一天

>>> print (datetime.datetime.now()+datetime.timedelta(days=1)).strftime("%Y-%m-%d %H:%M:%S")

2019-07-12 14:32:37

加 一小时

>>> print (datetime.datetime.now()+datetime.timedelta(hours=1)).strftime("%Y-%m-%d %H:%M:%S")

2019-07-11 15:33:37

也可以使用timedelta方法对指定时间进行加减:首先对指定时间进行处理

strTime = '2019-07-11 11:03' # 给定一个时间,此是个字符串

startTime = datetime.datetime.strptime(strTime, "%Y-%m-%d %H:%M") # 把strTime转化为时间格式,后面的秒位自动补位的

print startTime

print startTime.strftime("%Y-%m-%d %H:%M") # 格式化输出,保持和给定格式一致

# startTime时间加 一分钟

startTime2 = (startTime + datetime.timedelta(minutes=2)).strftime("%Y-%m-%d %H:%M")

print startTime2

输出:

2019-07-11 11:03:00

2019-07-11 11:03

2019-07-11 11:05

Process finished with exit code 0

标签:11,07,python,加减,datetime,2019,print,strftime

来源: https://www.cnblogs.com/monogem/p/11170011.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值