Home > Article > Backend Development > Python - convert string to date
The standard module datetime in Python can convert strings to dates
from datetime import datetime
text = '2012-09-20'
y = datetime.strptime(text, '%Y-%m-% d')
print(y)
z = datetime.now()
diff = z - y
print(diff)
Output in a specific format
nice_z = datetime.strftime(z, '%A %B %d, %Y')
print(nice_z)
datetime.strftime performance is very poor, write a function below
from datetime import datetime
def parse_ymd(s):
year_s, mon _s , day_s = s.split('-')
return datetime(int(year_s), int(mon_s), int(day_s))