2014-05-22 32 views
1

我正在从一个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 
+1

为什么不使用datetime strftime函数 – abhishekgarg

+2

你看过['strptime'](https://docs.python.org/2/library/datetime.html#datetime.datetime.strptime)吗? – jonrsharpe

+0

对不起,是的,我的意思是'strptime' – abhishekgarg

回答

2

找到更多这方面的信息,您可以潜在地使用datetime.datetime.strptime函数来获取,然后可以通过strftime进行格式化,以任何你想要的格式datetime对象。

>>> ts = "Thu May 22 15:40:24 +0000 2014" 
>>> dt = datetime.datetime.strptime(ts, "%a %b %d %H:%M:%S +0000 %Y") 
>>> dt.strftime("%Y-%m-%d") 
'2014-05-22' 

然而,有一个告诫说strptime不会在Python 2.处理时区偏移以及只要时区是恒定的(+0000)你可以硬编码到您的格式字符串。如果您使用的是Python 3,则可以使用%z来匹配时区偏移量,但在Python 2中不起作用。

另外请注意,我用%b以上月 - 即在版本月份名称相匹配。如果API实际返回长版本(很难说,因为您使用了在您的示例中从未缩短的一个月),您需要改为%B

+0

%z在python 2中完全不工作? –

+0

@PadraicCunningham我相信这是正确的(尽管OP没有指定Python版本)。稍作修改以澄清何时有用。 – Amber

+0

谢谢,那是我一直在寻找的东西:) – Sebastian

2

你可以做这样的事情

import datetime 

time = 'Thu May 22 15:40:24 +0000 2014' 

new_time = datetime.datetime.strptime(time, "%a %b %d %H:%M:%S +0000 %Y") 

print new_time.strftime("%Y-%d-%m") 

Python Doc.

相关问题