我正在从一个API中收集数据,该API以下列格式返回一个时间戳:'Thu May 22 15:40:24 +0000 2014',但是,我需要转换它变成我的数据库的YYYY-MM-DD。我写了一个函数来做到这一点,但它非常难看,我想知道是否有人试图用一些Python标准库模块来做到这一点,例如datetime
?寻找一种更简单的方式来解析Python中的时间戳
time = 'Thu May 22 15:40:24 +0000 2014'
def simplify_date(timestamp):
"""
Converts a timestamp of the format
'Thu May 22 15:40:24 +0000 2014' into a
date string YYYY-MM-DD, e.g., '2014-05-22'.
"""
months = {'Jan':'01', 'Feb':'02', 'Mar':'03',
'Apr':'04', 'May':'05', 'Jun':'06',
'Jul':'07', 'Aug':'08', 'Sep':'09',
'Oct':'10', 'Nov':'11', 'Dec':'12'
}
t = timestamp.split()
date = '%s-%s-%s' %(t[-1], months[t[1]], t[2])
return date
print(simplify_date(time))
2014-05-22
为什么不使用datetime strftime函数 – abhishekgarg
你看过['strptime'](https://docs.python.org/2/library/datetime.html#datetime.datetime.strptime)吗? – jonrsharpe
对不起,是的,我的意思是'strptime' – abhishekgarg