如何将字符串的时间形式转化成时间,并做差?下面将给出python的代码时间,字符串转时间通过截取年月日时分秒位置的值做int转化实现,做差直接调用的是datetime函数实现,可以选择返回秒,分,时,天。
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# author:SingWeek
import datetime
def data_time(datatime):
"""
从字符串中提取:年-月-日-时-分-秒
:param datatime: 输入字符串时间
:return: 返回时间
"""
second=int(datatime[-2:])
minute=int(datatime[-4:-2])
hour=int(datatime[-6:-4])
day=int(datatime[-8:-6])
month=int(datatime[4:6])
year=int(datatime[0:4])
return year,month,day,hour,minute,second
def sub_time(start,end,ctype='second'):
"""
时间差求取函数
:param start: 开始时间,字符串形式
:param end: 结束时间,字符串形式
:param ctype: 根据ctype返回秒、分、时、天
:return: 返回时间差
"""
year1, month1, day1, hour1, minute1, second1=data_time(start)
year2, month2, day2, hour2, minute2, second2=data_time(end)
time1 = datetime.datetime(year1, month1, day1, hour1, minute1, second1)
time2 = datetime.datetime(year2, month2, day2, hour2, minute2, second2)
if ctype=='second':
return (time2-time1).seconds
elif ctype=='minute':
return int((time2-time1).seconds/60)
elif ctype=='hour':
return int((time2 - time1).seconds / 3600)
elif ctype=='day':
return (time2-time1).days