2010-07-20 34 views
2

我正在使用exif.py库。致电python时间问题

tags=exif.process_file(...) 

我想检索图像被捕获的时间。所以我继续

t =tags['Image DateTime'] if tags.has_key('Image DateTime') else time.time() 

现在我想存储t在django的数据库。对于T必须在形式2010-07-20 14时37分12秒,但显然EXIF提供2010:07:20 14时37分12秒然而,当我去

type(t) 

返回“实例”,而不是浮动哪个是

type(time.time()) 

或'str'是字符串的类型。我如何解析EXIF给我的值将其填充到django模型中?

回答

2

使用time.strptime()解析str()值,比时间元组格式化为任何所需的形式。

一个示例,使用EXIF返回的'Image DateTime'属性。

>>> e1['Image DateTime'] 
(0x0132) ASCII=2007:09:06 06:37:51 @ 176 
>>> str(e1['Image DateTime']) 
'2007:09:06 06:37:51' 
>>> 
>>> tag = time.strptime(str(e1['Image DateTime']),"%Y:%m:%d %H:%M:%S") 
>>> tag 
time.struct_time(tm_year=2007, tm_mon=9, tm_mday=6, tm_hour=6, tm_min=37, tm_sec=51,tm_wday=3, tm_yday=249, tm_isdst=-1) 
>>> time.strftime("%Y-%m-%d %H:%M:%S", tag) 
'2007-09-06 06:37:51' 
>>> 
0

它看起来像exif.py返回IFD_Tag的一个实例。你想要的值可能在t.values中。您还可以使用datetime.strptime()来解析从exif数据获得的字符串。

1

Django最适合datetime对象。字符串可以转换为datetime,但是你不应该关注字符串。你应该专注于创建一个适当的对象。

选择1.找出什么样的实际时间是exif时间。而不是type(t),做t.__class__看看它真的是什么。另外,所以dir(t)看看它有什么方法。它可能会创建一个适当的浮点值或time.struct_time值的方法。

Choice 2.使用datetime.datetime.strptime解析时间字符串以创建适当的datetime对象。阅读:http://docs.python.org/library/datetime.html#datetime.datetime.strptime

0

假设标签[ '图像的DateTime'],如果存在的话,返回像 “2010:07:20十四时37分12秒” 的字符串,那么你可以使用:

if tags.has_key('Image DateTime'): 
    t = tags['Image DateTime'].replace(':', '-' , 2) 
else: 
    t = time.strftime('%Y-%m-%d %H:%M:%S') 

replace修复从EXIF时间字符串:

>>> '2010:07:20 14:37:12'.replace(':', '-', 2) 
    '2010-07-20 14:37:12' 

如果你想GMT,而不是本地时间使用

time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime())