python 時間戳是什麼 Python使用時間戳

2021-10-12 11:20:39 字數 2044 閱讀 1194

1.將字串的時間轉換為時間戳

方法:a = "2013-10-10 23:40:00"

將其轉換為時間陣列

importtime

timearray = time.strptime(a, "%y-%m-%d %h:%m:%s")

轉換為時間戳:

timestamp = int(time.mktime(timearray))

timestamp == 1381419600

2.字串格式更改

如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)

3.時間戳轉換為指定格式日期:

方法一:

利用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"

4.獲取當前時間並轉換為指定日期格式

方法一:

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")

5.獲得三天前的時間

方法: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,能夠轉換為其它的隨意格式了

python時間戳是什麼意思 Python 時間戳

import time 返回時間戳 print time.time 返回時間戳 print time.gmtime 返回utc時間戳 print time.localtime time.time 86400 返回當地的時間戳 print time.strftime y m d time.localt...

python 時間 時間戳 轉換

1.簡介 在編寫 時,往往涉及時間 日期 時間戳的相互轉換。python datetime 新增時區 import datetime from dateutil import tz tz sh tz.gettz asia shanghai print datetime.datetime.now tz...

python教程是什麼 Python是什麼?

python是物件導向,高階語言,解釋,動態和多用途程式語言。python易於學習,而且功能強大,功能多樣的指令碼語言使其對應用程式開發具有吸引力。python的語法和動態型別具有其解釋性質,使其成為許多領域的指令碼編寫和快速應用程式開發的理想語言。python支援多種程式設計模式,包括物件導向程式...