Kate D.
Kate D.

Reputation: 23

convert string to date in Python

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)

Upvotes: 1

Views: 85

Answers (2)

Bubble Bubble Bubble Gut
Bubble Bubble Bubble Gut

Reputation: 3358

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)

Upvotes: 1

fferri
fferri

Reputation: 18940

Use capital Y for four-digits year:

audit_date_final = datetime.datetime.strptime(audit_date_slice, '%Y-%m-%d').date()

Upvotes: 3

Related Questions