String to date
Your application accepts input in string format , But you want to convert them into datetime Object to perform non string operations on it .
Use Python The standard module of datetime This problem can be easily solved . such as ：
'2012-09-20' > y = datetime.strptime(text, '%Y-%m-%d') > z = datetime.now() > diff = z - y > diff datetime.timedelta(3, 77824, 177393) >> from datetime import datetime > text =
datetime.strptime() Method supports a lot of formatting code , such as %Y representative 4 Number year , %m Represents a two digit month . It's also worth noting that these formatting placeholders can be used in reverse , Output the date to the specified format string form .
such as , Suppose your code generates a datetime object , You want to format it into a nice readable form and put it on top of an automatically generated letter or report ：
2012, 9, 23, 21, 37, 4, 177393) > nice_z = datetime.strftime(z, '%A %B %d, %Y') > nice_z 'Sunday September 23, 2012' >> z datetime.datetime(
Another thing to note is , strptime() The performance is much worse than you think , Because it uses pure Python Realization , And you have to deal with all the system local settings . If you want to parse a large number of dates in your code and already know the exact format of the date string , To get a better performance solution . such as , If you already know, so the date format is YYYY-MM-DD , You can implement an analytic function like this ：
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))
In practice , The function ratio is datetime.strptime() fast 7 More than double . If you're dealing with a lot of date data , So it's better to think about this plan ！