Home  >  Article  >  Backend Development  >  Python - convert string to date

Python - convert string to date

巴扎黑
巴扎黑Original
2016-11-26 09:40:211805browse

The standard module datetime in Python can convert strings to dates

Python code

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

Java code

nice_z = datetime .strftime(z, '%A %B %d, %Y')

print(nice_z)

datetime.strftime performance is very poor, write a function below

Python code

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))


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn