1

Can this be done any way more pythonic?

>>> import datetime
>>> date = '20131018'
>>> date
'20131018'
>>> year, month, day = date[0:4], date[4:6], date[6:]
>>> datetime.date(int(year), int(month), int(day))
datetime.date(2013, 10, 18)

Thanks

0

1 Answer 1

4

Python already has a built-in way of parsing dates from strings in the datetime package, namely datetime.datetime.strptime:

>>> from datetime import datetime as dt
>>> date = '20131018'
>>> dt.strptime(date, "%Y%m%d").date()
datetime.date(2013, 10, 18)

See the docs for all of the available format / parsing options.

Sign up to request clarification or add additional context in comments.

2 Comments

strptime returns a datetime, not a date as your example shows. You need to call date() on the newly created datetime: dt.strptime(date, "%Y%m%d").date().
@StevenRumbalski - valid point - I've updated my answer. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.