Python 时间格式化(转)

From:http://www.cnblogs.com/65702708/archive/2011/04/17/2018936.html

http://www.wklken.me/posts/2015/03/03/python-base-datetime.html

Python格式化日期时间的函数为datetime.datetime.strftime();由字符串转为日期型的函数为:datetime.datetime.strptime(),两个函数都涉及日期时间的格式化字符串,列举如下:

 1 %a Abbreviated weekday name 
 2 %A Full weekday name 
 3 %b Abbreviated month name 
 4 %B Full month name 
 5 %c Date and time representation appropriate for locale 
 6 %d Day of month as decimal number (01 - 31) 
 7 %H Hour in 24-hour format (00 - 23) 
 8 %I Hour in 12-hour format (01 - 12) 
 9 %j Day of year as decimal number (001 - 366) 
10 %m Month as decimal number (01 - 12) 
11 %M Minute as decimal number (00 - 59) 
12 %p Current locale's A.M./P.M. indicator for 12-hour clock 
13 %S Second as decimal number (00 - 59) 
14 %U Week of year as decimal number, with Sunday as first day of week (00 - 51) 
15 %w Weekday as decimal number (0 - 6; Sunday is 0) 
16 %W Week of year as decimal number, with Monday as first day of week (00 - 51) 
17 %x Date representation for current locale 
18 %X Time representation for current locale 
19 %y Year without century, as decimal number (00 - 99) 
20 %Y Year with century, as decimal number 
21 %z, %Z Time-zone name or abbreviation; no characters if time zone is unknown 
22 %% Percent sign

举一个例子:

ebay中时间格式为‘Sep-21-09 16:34’

则通过下面代码将这个字符串转换成datetime

c = datetime.datetime.strptime('Sep-21-09 16:34','%b-%d-%y %H:%M');

#打印C
c
datetime.datetime(2009, 9, 21, 16, 34)

又如:datetime转换成字符串

datetime.datetime.now().strftime('%b-%d-%y %H:%M:%S');
'Sep-22-09 16:48:08'
原文地址:https://www.cnblogs.com/xiaoerlang/p/6496034.html