本文目录一览:
- 1、怎么用Python实现时间加减运算?
- 2、怎么用Python实现时间加减运算?
- 3、python日期加减比较问题请教
- 4、python3 环境,如何计算时间的比较和加减
- 5、python 时间字符串相减
怎么用Python实现时间加减运算?
import time
import datetime
# 将时间str转化为普通时间类型,用于计算
startTime = datetime.datetime.strptime(startTime,"%Y-%m-%d %H:%M:%S")
endTime = datetime.datetime.strptime(endTime,"%Y-%m-%d %H:%M:%S")
sample_time = datetime.datetime.strptime(time_string, '%Y-%m-%dT%H:%M:%SZ')
(第一个参数为字符串形式的时间,第二个参数为该字符串形式时间的格式)
# 时间运算
seconds = (endTime- startTime).seconds
hours=(endTime- startTime).hours
day=(endTime- startTime).day
# 计算时间差
startTime = time.clock()
endTime = time.clock()
runTime = endTime - startTime
怎么用Python实现时间加减运算?
使用timedelta就可以直接进行运算。
datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
timedelta可以传入天数、小时、分、秒、星期、毫秒等。
python日期加减比较问题请教
# time模块实现, 也是自带的
# 字符串不好计算~但是时间戳是固定的呀...
# 计算结果中, 假定今天24日, 输入24, 输出0天, 输入25, 输出-1天
import time
def f(tm):
stamp = time.mktime(time.strptime(tm, "%Y%m%d"))
diff = int((time.time() - stamp) // 86400)
if diff = 180:
return {tm: str(diff)}
else:
d = {}
while diff 180:
d[tm] = 180
stamp += 180 * 86400
diff = int((time.time() - stamp) // 86400)
# 注意这里time.gmtime()返回的是0时区日期, 需要处理时区问题
tm = time.strftime("%Y%m%d", time.gmtime(stamp - time.timezone))
else:
d[tm] = str(diff)
return d
if __name__ == '__main__':
tm = '20160325'
print(f(tm))
tm = '20171015'
print(f(tm))
# 结果输出, 注意: 字典是没有固定顺序的
'''
{'20160921': 180, '20170320': 180, '20170916': '38', '20160325': 180}
{'20171015': '9'}
'''
python3 环境,如何计算时间的比较和加减
显示5分钟前的时间
print(datetime.datetime.now() - datetime.timedelta(seconds = 5*60))
构造时间并显示时间差
d = datetime.datetime.now()
d = d.replace(hour = 9,minute = 30,second = 0)
print((datetime.datetime.now() - d))
python 时间字符串相减
from datetime import datetime
a = '12:13:50'
b = '12:28:21'
time_a = datetime.strptime(a,'%H:%M:%S')
time_b = datetime.strptime(b,'%H:%M:%S')
print (time_b - time_a).seconds