python's datetime has a function strptime ()
that converts a string type to a datetime type, but it cannot convert a string that is not padded with 0s.
(2020/04/03
can be converted, but 2020/4/3
cannot)
Note that there was an easy alternative.
If full-width characters are included, use some method to make full-width characters half-width and then execute. There are various methods, so choose the one you like.
Use the datetime constructor instead of strptime ()
.
https://docs.python.org/ja/3/library/datetime.html#datetime.datetime
class datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)
import datetime
import re
#Get a list of numbers contained in a string
l = re.findall(r"\d+", text)
#Make a list of strings a list of numbers
l = [int(s) for s in l]
#Specify the date and time in the datetime type constructor (expand the list and pass it)
date = datetime.datetime(*l)
import datetime
import re
text = "2020/4/2"
l = re.findall(r"\d+", text)
# l : ["2020", "4", "2"]
l = [int(s) for s in l]
# l : [2020, 4, 2]
date = datetime.datetime(*l)
# date = datetime.datetime(2020, 4, 2)
May be used for conversion from Japanese calendar to Western calendar (It is necessary to correspond to the "first year")
import datetime
import re
text = "April 3, 2nd year of Reiwa"
diff = 0
if text[:2]=="Reiwa":
diff = 2018
else:
# hoge
pass
l = re.findall(r"\d+", text)
l = [int(s) for s in l]
l[0] += diff
date = datetime.datetime(*l)
Recommended Posts