s1= ' 20120125 ';
6 s2= ' 20120216 ';
7 a=time.strptime (S1, '%y%m%d ');
8 B=time.strptime (s2, '%y%m%d ');
9 A_datetime=datetime.datetime (*a[:3]);
Ten B_datetime=datetime.datetime (*b[:3]);
Print b_datetime-a_datetime;
http://blog.csdn.net/nankaihunter/article/details/5003327
In order to extract the time from the string and compare it, so with this problem, how to convert the string to a datetime type
1. Conversion of string to time type
>>> Import Time
>>> timestr = "time2009-12-14"
>>> t = time.strptime (TIMESTR, "time%y-%m-%d")
>>> Print T
(2009, 12, 14, 0, 0, 0, 0, 348,-1)
>>> type (t)
<type ' Time.struct_time ' >
>>>
As shown in the code, the first argument is the string to be converted, the second argument is the format of the time in the string, and the strptime is used for conversion.
The corresponding function strftime is to convert the time type to the corresponding string
The following is a summary of formatting symbols
%a the abbreviated Weekday name of the week, abbr.
%A the full name of the week Weekday name, full
%b month name, abbr.
The full name of the%B month, month name, full
The time string for the date of the%c standard complete date representation
The day of the month in%d decimal notation
%H 24-Hour hour Hour (24-hour clock)
%I 12-Hour hour Hour (12-hour clock)
%j decimal represents the day of the Week of the year
%m decimal indicates month months
%M minutes by 10 o'clock Minute number
%s Decimal seconds Second number
%u the week of the year, the Sunday as the first day (value from 0 to Week number) (Sunday-weekday)
%w Decimal Day of the week (value from 0 to 6, Sunday is 0) weekday number
%W Week of the year, Monday as the first day (value from 0 to Week) number (Monday weekday)
The date string for%x standard complete date representation (e.g. 13/01/08)
%x Standard Time series complete representation (e.g. 17:02:10)
%y a decimal year without a century (value from 0 to a) years number within century
%Y with century part 10 year number
%z,%z the time zone name and returns a null character if the time zone name cannot be obtained. Name of time Zone
Percent hundred percent semicolon
Conversion of 2.time types to datetime types
This is a simple step, using the DateTime function, the code is as follows
>>> Import datetime
>>> d = datetime.datetime (* t[:6])
>>> Print D
2009-12-14 00:00:00
>>> Type (d)
<type ' Datetime.datetime ' >
>>>
"Python" Time and DateTime type conversions, string variables to date type variables