Jason
Jason

Reputation: 11363

Easier way to create date object from string

I'm working on an image upload utility, and part of the functionality is to parse the IPTC and EXIF data of the images.

IPTCInfo gets the information I need, but the date fields are in the format 20130925.

Now, I can break that integer up into 2013 09 25 and create a date object. Before I do so, is there already existing functionality to solve this issue?

Upvotes: 1

Views: 501

Answers (2)

space
space

Reputation: 417

You can use datetime.strptime:

>>> import datetime
>>> datetime.datetime.strptime("20130925","%Y%m%d").date()
datetime.date(2013, 9, 25)

Upvotes: 1

abarnert
abarnert

Reputation: 366083

The date class doesn't have a string-parsing function, but the datetime class does, strptime.

So, first make a datetime, then extract the date part of it:

>>> s = '20130925'
>>> dt = datetime.datetime.strptime(s, '%Y%m%d')
>>> d = dt.date()
>>> d
datetime.date(2013, 9, 25)

If you don't understand where the '%Y%m%d' comes from, see strftime() and strptime() Behavior.

Upvotes: 8

Related Questions