主要用到两个库,time和datetime
import time
import datetime
import re
# 格式化日期字符串
def formatDateStr(date_string, target_pattern='%Y-%m-%d'):
# 日期格式转换(yyyy-MM-dd HH:mm:ss,yyyy/MM/dd,yyyyMMdd
patterns = {'%Y-%m-%d %H:%M:%S': '\d{4}-[01]\d-[0123]\d\s{1,2}[012]\d:[0-5]\d:[0-5]\d',
'%Y/%m/%d': '\d{4}/[01]\d/[0123]\d',
'%Y%m%d': '\d{4}[01]\d[0123]\d'}
for key, value in patterns.items():
if re.match(value, date_string, re.M | re.I):
# 字符转换为tuple
time_tuple = time.strptime(date_string, key)
# tuple转化为字符串
return time.strftime(target_pattern, time_tuple)
else:
pass
return ''
def formatDateStr2(date_string, target_pattern='%Y-%m-%d'):
# 日期格式转换(yyyy-MM-dd HH:mm:ss,yyyy/MM/dd,yyyyMMdd
patterns = {'%Y-%m-%d %H:%M:%S': '\d{4}-[01]\d-[0123]\d\s{1,2}[012]\d:[0-5]\d:[0-5]\d',
'%Y/%m/%d': '\d{4}/[01]\d/[0123]\d',
'%Y%m%d': '\d{4}[01]\d[0123]\d'}
for key, value in patterns.items():
if re.match(value, date_string, re.M | re.I):
# 字符转换为time
date = datetime.datetime.strptime(date_string, key)
# 获取年
year = datetime.datetime.strptime(date_string, key).year
# 获取月
month = datetime.datetime.strptime(date_string, key).month
# 获取日
day = datetime.datetime.strptime(date_string, key).day
return date.strftime(target_pattern)
else:
pass
return ''
def formatTimeStr(time_str, target_pattern='%H:%M:%S'):
patterns = {'%H:%M:%S': '[012]\d:[0-5]\d:[0-5]\d', '%H%M%S': '[012]\d[0-5]\d[0-5]\d'}
for key, value in patterns.items():
if re.match(value, time_str, re.M | re.I):
# 字符转换为tuple
time_tuple = time.strptime(time_str, key)
# tuple转化为字符串
return time.strftime(target_pattern, time_tuple)
else:
pass
return time_str
# 计算两个时间段的天数
def formatCycleTime(date_string):
# 日期格式转化2019.01.18-2019.03.15
patterns = {'%Y.%m.%d-%Y.%m.%d': '\d{4}\.[01]\d\.[0123]\d-\d{4}\.[01]\d\.[0123]\d',
'%Y/%m/%d-%Y/%m/%d': '\d{4}\/[01]\d\/[0123]\d-\d{4}\/[01]\d\/[0123]\d'}
for key, value in patterns.items():
if re.match(value, date_string, re.M | re.I):
dates = date_string.split('-')
startDate = dates[0]
endDate = dates[1]
d1 = datetime.datetime.strptime(startDate, key.split('-')[0])
d2 = datetime.datetime.strptime(endDate, key.split('-')[0])
return (d2 - d1).days
return ''
def parseTimeStamp2Date(timestamp):
# 时间戳转化为time
return time.localtime(timestamp)
def parseDate2TimeStamp(time_tuple):
# 转化为时间戳
return time.mktime(time_tuple)
if __name__ == '__main__':
str = '2019-08-29 23:59:49'
print(formatDateStr(str))
print(formatDateStr2(str))
运行结果:
时间字符串格式化