1

Python newbie here, so this is probably an easy question. I'm trying to extract part of a string and convert it to date format (there's no time involved). I'm trying to copy approaches I've seen online, but I get the message

ValueError: time data '2017-07-10' does not match format '%y-%m-%d'.

I'm probably using the wrong format somewhere, and I'm not sure how to proceed. Thanks very much for any suggestions you may have.

#convert the audit_date to a list so it can be
# sliced
audit_date_list = list(audit_date)
# Slice audit_date_list to get chars at indexes
# 13-22
# only, then join those chars
audit_date_slice = "".join(audit_date_list[13:23])
#convert audit_date_slice to date format
audit_date_final = datetime.datetime.strptime(audit_date_slice, '%y-%m-%d').date()
print(audit_date_final)
1
  • Hi, I see you're new to SO. If you feel an answer solved the problem, please mark it as 'accepted’ by clicking the green check mark. This helps keep the focus on older SO which still don't have answers. Commented May 1, 2018 at 18:31

2 Answers 2

3

Use capital Y for four-digits year:

audit_date_final = datetime.datetime.strptime(audit_date_slice, '%Y-%m-%d').date()
Sign up to request clarification or add additional context in comments.

Comments

1

If you don't want to remember the format, try using dateutil, it recognizes most of the formats and it's shipped with Anaconda.

from dateutil import parser

audit_date_final = parser.parse(audit_date_slice)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.