简体   繁体   中英

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)

使用大写字母Y表示四位数的年份:

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM