suppose I have a report that has the following name:
"REPORT NAME 0331", where 0331 refers to March 31th, 2020.
I was able to extract the 0331 through slicing:
name[-4:]
But I would like to now format 0331 into a valid date (ie, that I can then use to compare vs the date of another report, and determine which report is older).
EDIT: The format should be "2020-MM-DD"
How would that work?
The following code should work for what you described.
import datetime from datetime
month_date = '%m%d'
raw_value = '0331'
date = datetime.strptime(month_day_format, raw_value)
date = date.replace(year=2020)
report_date = date.strftime('%Y-%m-%d')
The report_date
captures the formatted date string.
Useful links to the datatime functions used:
You could use datetime.strptime()
, eg:
datetime.datetime.strptime('0331', '%m%d')
# datetime.datetime(1900, 3, 31, 0, 0)
and then you can use the datetime
object as detailed in the documentation .
try this one:
d = name[-4:]
res = datetime(2020, int(d[:2]),int(d[2:]))
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.