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

Python - convert string to date

巴扎黑
巴扎黑Original
2016-12-03 10:19:311208browse

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


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