1.將字串的時間轉換為時間戳
2.字串格式更改方法:
a = "2013-10-10 23:40:00"
將其轉換為時間陣列
import time
timearray = time.strptime(a, "%y-%m-%d %h:%m:%s")
轉換為時間戳:
timestamp = int(time.mktime(timearray))
timestamp == 1381419600
3.時間戳轉換為指定格式日期:如a = "2013-10-10 23:40:00",想改為 a = "2013/10/10 23:40:00"
方法:先轉換為時間陣列,然後轉換為其他格式
timearray = time.strptime(a, "%y-%m-%d %h:%m:%s")
otherstyletime = time.strftime("%y/%m/%d %h:%m:%s", timearray)
4.獲取當前時間並轉換為指定日期格式方法一:
利用localtime()轉換為時間陣列,然後格式化為需要的格式,如
timestamp = 1381419600
timearray = time.localtime(timestamp)
otherstyletime = time.strftime("%y-%m-%d %h:%m:%s", timearray)
otherstyletime == "2013-10-10 23:40:00"
方法二:
importdatetime
timestamp = 1381419600
datearray = datetime.datetime.utcfromtimestamp(timestamp)
otherstyletime = datearray.strftime("%y-%m-%d %h:%m:%s")
otherstyletime == "2013-10-10 23:40:00"
5.獲得三天前的時間方法一:
importtime
獲得當前時間時間戳
now = int(time.time()) ->這是時間戳
轉換為其他日期格式,如:"%y-%m-%d %h:%m:%s"
timearray = time.localtime(timestamp)
otherstyletime = time.strftime("%y-%m-%d %h:%m:%s", timearray)
方法二:
importdatetime
獲得當前時間
now = datetime.datetime.now() ->這是時間陣列格式
轉換為指定的格式:
otherstyletime = now.strftime("%y-%m-%d %h:%m:%s")
方法:
importtime
importdatetime
先獲得時間陣列格式的日期
threedayago = (datetime.datetime.now() - datetime.timedelta(days = 3))
轉換為時間戳:
timestamp = int(time.mktime(threedayago.timetuple()))
轉換為其他字串格式:
otherstyletime = threedayago.strftime("%y-%m-%d %h:%m:%s")
注:timedelta()的引數有:days,hours,seconds,microseconds
對於時間之間的格式:timestamp = 1381419600
先轉換為datetime
importdatetime
importtime
datearray = datetime.datetime.utcfromtimestamp(timestamp)
threedayago = datearray - datetime.timedelta(days = 3)
參考5,可以轉換為其他的任意格式了
%a 星期的簡寫。如 星期三為web
%a 星期的全寫。如 星期三為wednesday
%b 月份的簡寫。如4月份為apr
%b 月份的全寫。如4月份為april
%c: 日期時間的字串表示。(如: 04/07/10 10:43:39)
%d: 日在這個月中的天數(是這個月的第幾天)
%f: 微秒(範圍[0,999999])
%h: 小時(24小時制,[0, 23])
%i: 小時(12小時制,[0, 11])
%j: 日在年中的天數 [001,366](是當年的第幾天)
%m: 月份([01,12])
%m: 分鐘([00,59])
%p: am或者pm
%s: 秒(範圍為[00,61],為什麼不是[00, 59],參考python手冊_)
%u: 周在當年的週數當年的第幾周),星期天作為周的第一天
%w: 今天在這週的天數,範圍為[0, 6],6表示星期天
%w: 周在當年的週數(是當年的第幾周),星期一作為周的第一天
%x: 日期字串(如:04/07/10)
%x: 時間字串(如:10:43:39)
%y: 2個數字表示的年份
%y: 4個數字表示的年份
%z: 與utc時間的間隔 (如果是本地時間,返回空字串)
%z: 時區名稱(如果是本地時間,返回空字串)
%%: %% => %
Python 時間戳 字串 時間 轉換
平時對於時間的處理經常使用python的time和datetime模組,但是用來多次還是對其中的時間戳,字串和時間轉換應用的不太熟練,時間長了不使用就理不清楚,為此整理成文。時間戳,時間,字串之間的關係整理如下圖 時間戳 time.time 返回當前時間戳 seconds time.time tim...
python 字串時間轉成時間戳
示例一import time t 2020 10 31 12 44 27 將字串形式的時間轉換為時間元組 t time.strptime t,y m d h m s 將時間元組轉換為時間戳 t time.mktime t 1604119467.0 print t 示例二import time t m...
python 時間戳 時間字串轉換
使用time和datetime包進行轉換。環境python2.7.13。gmt 格林威治時間,bjt 北京時間。時間戳轉為時間字串 coding utf 8 時間戳 gmt 轉化為字串 bjt import time import datetime timestamp 1522165684 時間戳是...