import datetime import time # datetime.datetime(2015, 1, 1, 20, 23, 20) # -> '2015-01-01 20:23:20' def datetime_to_string(dt): return dt.strftime("%Y-%m-%d %H:%M:%S") # '2015-01-01 20:23:20' # -> datetime.datetime(2015, 1, 1, 20, 23, 20) def string_to_datetime(value): return datetime.datetime.strptime(value, "%Y-%m-%d %H:%M:%S") # '2015-01-01 20:23:20' # -> 1420115000.0 def string_to_timestamp(value): return time.mktime(string_to_datetime(value).timetuple()) # 1420115000.0 # -> '2015-01-01 20:23:20' def timestamp_to_string(value): return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(value)) # datetime.datetime(2016, 12, 8, 9, 20, 30, 229913) # -> 1481160030.0 def datetime_to_timestamp(value): return time.mktime(value.timetuple()) #datetime_to_timestamp(datetime.datetime.today()) # substract_datetime('2016-10-01 10:10:10', '2016-05-01 10:10:10').days # -153 # 内部只存储days,seconds,microseconds def substract_datetime(value1, value2): dt1 = string_to_datetime(value1) dt2 = string_to_datetime(value2) return dt2 - dt1 # substract_timestamp('2016-10-01 10:10:10', '2016-05-01 10:10:10') # -13219200.0 def substract_timestamp(value1, value2): ts1 = string_to_timestamp(value1) ts2 = string_to_timestamp(value2) return ts2 - ts1 # compare_datetime('2016-10-01 10:10:10', '2017-05-01 10:10:10') # True def compare_datetime(value1, value2): dt1 = string_to_datetime(value1) dt2 = string_to_datetime(value2) return dt2 > dt1 # datetime_add('2016-10-01 10:10:10', 10) # datetime.datetime(2016, 10, 11, 10, 10, 10) def datetime_add(value, days=0, hours=0, minutes=0): dt= string_to_datetime(value) return dt + datetime.timedelta(days=days, hours=hours, minutes=minutes) # datetime # datetime.datetime(2016, 12, 8, 9, 17, 51, 878174) #datetime.datetime.today() # datetime.datetime(2016, 12, 8, 9, 17, 31, 845853) #datetime.datetime.now()