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 startTimeprint 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:002019-07-11 11:032019-07-11 11:05Process finished with exit code 0

循环加时间

技术图片
startTime = ‘2019-07-11 23:30:00‘  # 输入一个时间,此是个字符串# endTime = ‘2019-07-11 15:35‘for i in range(3):    endTime = (datetime.datetime.strptime(startTime, "%Y-%m-%d %H:%M:%S") + datetime.timedelta(        days=1)).strftime("%Y-%m-%d %H:%M:%S")    print startTime,endTime    startTime = endTime

# 参数days=1(天+1) 可以换成 minutes=1(分钟+1)、seconds=1(秒+1)
技术图片
输出:
2019-07-11 23:30:00 2019-07-12 23:30:002019-07-12 23:30:00 2019-07-13 23:30:002019-07-13 23:30:00 2019-07-14 23:30:00Process finished with exit code 0

python 日期

评论关闭