开发者

python time problem

开发者 https://www.devze.com 2023-01-08 14:33 出处:网络
I am using the exif.py library. After calling tags=exif.process_file(...) i want to retrieve the time the image was captured. so i continue with

I am using the exif.py library. After calling

tags=exif.process_file(...)

i want to retrieve the time the image was captured. so i continue with

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

now i want to store t in django's database. For that t must be in the form 2010-07-20 14:37:12 but apparently exif delivers 2010:07:20 14:37:12 however when i go

type(开发者_Go百科t)

it returns 'instance' as opposed to float which is the result of

type(time.time())

or 'str' which is the type of string. How can I parse the value EXIF gave me to stuff it into the django model?


Use time.strptime() to parse the str() value, than format the time tuple to any desired form.

An example, using the 'Image DateTime' attribute returned by EXIF.

>>> 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'
>>> 


Django works best with datetime objects. Strings can be converted to datetime, but you should not focus on strings. You should focus on creating a proper datetime object.

Choice 1. Figure out what actual class the exif time is. Instead of type(t), do t.__class__ to see what it really is. Also, so dir(t) to see what methods it has. It may have methods which will create a proper float value or time.struct_time value.

Choice 2. Parse the time string with datetime.datetime.strptime to create a proper datetime object. Read this: http://docs.python.org/library/datetime.html#datetime.datetime.strptime


It looks like exif.py returns an instance of IFD_Tag. The values you want may be in t.values. You can also use datetime.strptime() to parse the string you get from the exif data.


Assuming that tags['Image DateTime'], if present, returns a string like "2010:07:20 14:37:12" then you can use:

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

replace fixes the time-string from exif:

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

If you want GMT rather than local time use

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

精彩评论

暂无评论...
验证码 换一张
取 消