任给两组时间,求出它们的时间差。例如:从7时10分52秒到10时20分50秒有几时几分几秒?
OverflowError: mktime argument out of range
。 (2018, 1, 1, time1array[3], time1array[4], time1array[5], 1, 1, 0)
。'''
字符串s : [str] '7时10分52秒'
日期格式数组timearray : [time.struct_time] time.struct_time(tm_year=2016, tm_mon=7, tm_mday=31, tm_hour=11, tm_min=17, tm_sec=17, tm_wday=6, tm_yday=213, tm_isdst=0)
时间戳timestamp : [floating point number] 1469938332.0
'''
# 其中日期格式数组中的tm_wday,tm_yday,tm_isdst三个参数的意义如下:
# weekday (0-6, Monday is 0)
# Julian day (day in the year, 1-366)
# DST (Daylight Savings Time) flag (-1, 0 or 1) 是否是夏令时
# 字符串与日期格式数组之间的转换
timearray = time.strptime('7时10分52秒', '%H时%M分%S秒')
s = time.strftime('%H时%M分%S秒', timearray)
# 日期格式数组与时间戳之间的转换
timestamp = int(time.mktime(timearray))
timestamp = time.gmtime(timearray)
timearray = time.localtime(timestamp)
# 字符串与时间戳的转换
s = time.ctime(timestamp)
# 返回当前的时间戳
timestamp = time.time()
# datetime模块中的类
datetime.date # 表示日期的类。常用的属性有year, month, day;
datetime.time # 表示时间的类。常用的属性有hour, minute, second, microsecond;
datetime.datetime # 表示日期时间。
datetime.timedelta # 表示时间间隔,即两个时间点之间的长度。
datetime.tzinfo # 与时区有关的相关信息
# 字符串与datetime对象之间的转换
datetime1 = datetime.datetime.strptime('7时10分52秒', '%H时%M分%S秒')
# timedelta中的seconds,days,minseconds属性
seconds = datetime.datetime,timedelta.seconds
minseconds = datetime.datetime,timedelta.minseconds
days = datetime.datetime,timedelta.days
# time模块
import time
def cal_difftime(time1, time2):
# 字符串转换成日期格式数组
time1array = time.strptime(time1, '%H时%M分%S秒')
time2array = time.strptime(time2, '%H时%M分%S秒')
# 因为默认年份为1900,转换时间戳的时候会出现报错
# OverflowError: mktime argument out of range
# timearray属于元组,不能修改其值
# 所以我对其年份进行了修改
time1array = (2018, 1, 1, time1array[3], time1array[4], time1array[5], 1, 1, 0)
time2array = (2018, 1, 1, time2array[3], time2array[4], time2array[5], 1, 1, 0)
# 日期格式数组转换成时间戳
time1stamp = int(time.mktime(time1array))
time2stamp = int(time.mktime(time2array))
# 计算时间戳时间差
timestamp = time2stamp - time1stamp
m, s = divmod(timestamp, 60)
h, m = divmod(m, 60)
difftime = "%02d时%02d分%02d秒" % (h, m, s)
return difftime
print cal_difftime('7时10分52秒', '10时20分50秒')
# datetime模块之一字符串化
import datetime
def cal_difftime(time1, time2):
# 字符串转换为datetime类型
times1 = datetime.datetime.strptime(time1, "%H时%M分%S秒")
times2 = datetime.datetime.strptime(time2, "%H时%M分%S秒")
# 利用datetime计算时间差并格式化输出
times = str(times2 - times1).split(':')
difftime = times[0]+'时'+times[1]+'分'+times[2]+'秒'
return difftime
print cal_difftime('7时10分52秒', '10时20分50秒')
# datetime模块之二divmod()函数
import datetime
def cal_difftime(time1, time2):
# 字符串转换为datetime类型
times1 = datetime.datetime.strptime(time1, "%H时%M分%S秒")
times2 = datetime.datetime.strptime(time2, "%H时%M分%S秒")
# 利用datetime计算时间差并格式化输出
times = (times2 - times1).seconds
m, s = divmod(timestamp, 60)
h, m = divmod(m, 60)
difftime = "%02d时%02d分%02d秒" % (h, m, s)
return difftime
print cal_difftime('7时10分52秒', '10时20分50秒')
如果有不对之处或者更好的思路,欢迎私信…