Convert a python datetime string to a Unix Timestamp
Today, I encountered a problem when I used python to write a small program for capturing web pages. The time string on the page, for example, '(17:38:49)', needs to be converted
UNIX timestamp. The strtotime function was previously written in PHP and was not found in Python. The following is an example on the Internet:
View Source
Print?
2 |
s =
datetime.datetime( 2009 , 1 , 1 )
|
3 |
time.mktime(s.timetuple()) |
Then write the regular expression on your own and extract the number and use the above method. The leading zero can be removed using int ().
After writing it online, I accidentally found the correct solution:
View Source
Print?
2 |
s =
'(2011-07-01 17:38:49)' |
3 |
s =
s.lstrip( '(' ).rstrip( ')' )
|
4 |
d =
datetime.datetime.strptime(s, "%Y-%m-%d %H:%M:%S" )
# See the following table for format characters |
5 |
print time.mktime(d.timetuple())
|
Time and date formatting symbols in Python:
% Y two-digit year (00-99)
% Y indicates the four-digit year (000-9999)
% M month (01-12)
One day in % d month (0-31)
% H hour in 24-hour format (0-23)
% I 12-hour (01-12)
% M minutes (00 = 59)
% S seconds (00-59)
% A local simplified week name
% A local full week name
% B local simplified month name
% B local full month name
% C local Date and Time
% J one day in the year (001-366)
% P local equivalent of a. m. or P. M.
% U number of weeks in a year (00-53) Sunday is the start of the week
% W Week (0-6), Sunday is the beginning of the week
% W number of weeks in a year (00-53) Monday is the start of the week
% X local date Representation
% X Local Time Representation
% Z Current Time Zone name
% Itself