1. 程式人生 > >【python】time 和datetime類型轉換,字符串型變量轉成日期型變量

【python】time 和datetime類型轉換,字符串型變量轉成日期型變量

-h with ptime 世紀 represent 字符串轉換 代碼 mes ear

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]);
10 b_datetime=datetime.datetime(*b[:3]);
11 print b_datetime-a_datetime;

http://blog.csdn.net/nankaihunter/article/details/5003327

為了從字符串中提取時間,並進行比較,因此有了這個問題,如何將字符串轉換成datetime類型

1.字符串與time類型的轉換

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

如代碼所示使用strptime進行轉換,第一個參數是要轉換的字符串,第二個參數是字符串中時間的格式

與之對應的有函數strftime,是將time類型轉換相應的字符串

下面是格式化符號匯總

  %a 星期幾的簡寫 Weekday name, abbr.
  %A 星期幾的全稱 Weekday name, full
  %b 月分的簡寫 Month name, abbr.
  %B 月份的全稱 Month name, full
  %c 標準的日期的時間串 Complete date and time representation
  %d 十進制表示的每月的第幾天 Day of the month
  %H 24小時制的小時 Hour (24-hour clock)
  %I 12小時制的小時 Hour (12-hour clock)
  %j 十進制表示的每年的第幾天 Day of the year
  %m 十進制表示的月份 Month number
  %M 十時制表示的分鐘數 Minute number
  %S 十進制的秒數 Second number
  %U 第年的第幾周,把星期日做為第一天(值從0到53)Week number (Sunday first weekday)
  %w 十進制表示的星期幾(值從0到6,星期天為0)weekday number
  %W 每年的第幾周,把星期一做為第一天(值從0到53) Week number (Monday first weekday)
  %x 標準的日期串 Complete date representation (e.g. 13/01/08)
  %X 標準的時間串 Complete time representation (e.g. 17:02:10)
  %y 不帶世紀的十進制年份(值從0到99)Year number within century
  %Y 帶世紀部分的十制年份 Year number
  %z,%Z 時區名稱,如果不能得到時區名稱則返回空字符。Name of time zone
  %% 百分號

2.time類型與datetime類型的轉換

這一步比較簡單,使用datetime函數,代碼如下

>>> import datetime
>>> d = datetime.datetime(* t[:6])
>>> print d
2009-12-14 00:00:00

>>> type(d)
<type ‘datetime.datetime‘>
>>>

【python】time 和datetime類型轉換,字符串型變量轉成日期型變量