python 字串轉時間

2021-06-20 10:33:06 字數 1882 閱讀 8106

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;

為了從字串中提取時間,並進行比較,因此有了這個問題,如何將字串轉換成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)

>>>

如**所示使用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)

>>> 

字串轉時間

由於js傳資料到後台很多時候把時間傳到控制器傳的是字串,這個時候就需要用應該很簡單的方法去轉時間了。可以看到這個input標籤所得到的時間為下圖這個時間。然後斷點看js 裡面得到的時間字串的所有傳到控制器的時候只能用字串來接收他 這裡得到了時間為字串就可以去提交了。第乙個方法是如下 直接宣告date...

php 字串轉時間戳 php字串轉時間戳

php字串轉時間戳 在php中可以使用 strtotime 函式將字串轉為時間戳。strtotime說明和用法 strtotime 將任何字串的日期時間描述解析為 unix 時間戳strtotime string time int now time int 本函式預期接受乙個包含美國英語日期格式的字...

Python 字串轉浮點型,列表轉字串

爬蟲過程中,採集的資料常以str或float存入資料庫 遇到含小數點的文字,需要轉換成浮點型xpath 或re.findall 提取資訊返回列表,列表可能為空,不便存進資料庫。a float 1.21 print a import numpy as np ls 1.2 3 0.5 array np....