Python中日期格式化是非常常見的操作,Python 中能用很多方式處理日期和時間,轉換日期格式是一個常見的功能。Python 提供了一個 time 和 calendar 模塊可以用於格式化日期和時間。時間間隔是以秒為單位的浮點小數。每個時間戳都以自從格林威治時間1970年01月01日00時00分00秒起經過了多長時間來表示。
注: 以下代碼在Python3下運行通過, Python2下未經測試
1. 基本方法
獲取當前日期:time.time()
獲取元組形式的時間戳:time.local(time.time())
格式化日期的函數(基於元組的形式進行格式化):
(1)time.asctime(time.local(time.time()))
(2)time.strftime(format[,t])
將格式字符串轉換為時間戳:
time.strptime(str,fmt='%a %b %d %H:%M:%S %Y')
延遲執行:time.sleep([secs]),單位為秒
2. 格式化符號
python中時間日期格式化符號:
%y 兩位數的年份表示(00-99)
%Y 四位數的年份表示(000-9999)
%m 月份(01-12)
%d 月內中的一天(0-31)
%H 24小時制小時數(0-23)
%I 12小時制小時數(01-12)
%M 分鍾數(00=59)
%S 秒(00-59)
%a 本地簡化星期名稱
%A 本地完整星期名稱
%b 本地簡化的月份名稱
%B 本地完整的月份名稱
%c 本地相應的日期表示和時間表示
%j 年內的一天(001-366)
%p 本地A.M.或P.M.的等價符
%U 一年中的星期數(00-53)星期天為星期的開始
%w 星期(0-6),星期天為星期的開始
%W 一年中的星期數(00-53)星期一為星期的開始
%x 本地相應的日期表示
%X 本地相應的時間表示
%Z 當前時區的名稱
%% %號本身
3. 常用用法
3.1 將字符串的時間轉換為時間戳
方法:
1
2
3
4
5
6
7
|
import time
t = "2017-11-24 17:30:00"
#將其轉換為時間數組
timeStruct = time.strptime(t, "%Y-%m-%d %H:%M:%S" )
#轉換為時間戳:
timeStamp = int (time.mktime(timeStruct))
print (timeStamp)
|
結果:
1511515800
3.2 時間戳轉換為指定格式日期
代碼:
1
2
3
4
|
timeStamp = 1511515800
localTime = time.localtime(timeStamp)
strTime = time.strftime( "%Y-%m-%d %H:%M:%S" , localTime)
print (strTime)
|
結果:
2017-11-24 17:30:00
3.3 格式切換
把-分割格式2017-11-24 17:30:00 轉換為斜杠分割格式: 結果:2017/11/24 17:30:00
代碼:
1
2
3
4
5
6
|
import time
t = "2017-11-24 17:30:00"
#先轉換為時間數組,然后轉換為其他格式
timeStruct = time.strptime(t, "%Y-%m-%d %H:%M:%S" )
strTime = time.strftime( "%Y/%m/%d %H:%M:%S" , timeStruct)
print (strTime)
|
結果:
2017/11/24 17:30:00
3.4 獲取當前時間並轉換為指定日期格式
1
2
3
4
5
6
7
|
import time
#獲得當前時間時間戳
now = int (time.time())
#轉換為其他日期格式,如:"%Y-%m-%d %H:%M:%S"
timeStruct = time.localtime(now)
strTime = time.strftime( "%Y-%m-%d %H:%M:%S" , timeStruct)
print (strTime)
|
結果:
2017-11-24 18:36:57
3.5 獲得三天前的時間的方法
1
2
3
4
5
6
7
8
9
|
import time
import datetime
#先獲得時間數組格式的日期
threeDayAgo = (datetime.datetime.now() - datetime.timedelta(days = 3 ))
#轉換為時間戳:
timeStamp = int (time.mktime(threeDayAgo.timetuple()))
#轉換為其他字符串格式:
strTime = threeDayAgo.strftime( "%Y-%m-%d %H:%M:%S" )
print (strTime)
|
結果:
2017-11-21 18:42:52
注:timedelta()的參數有:days,hours,seconds,microseconds
3.6 使用datetime模塊來獲取當前的日期和時間
1
2
3
4
5
6
7
8
9
10
11
|
import datetime
i = datetime.datetime.now()
print ( "當前的日期和時間是 %s" % i)
print ( "ISO格式的日期和時間是 %s" % i.isoformat() )
print ( "當前的年份是 %s" % i.year)
print ( "當前的月份是 %s" % i.month)
print ( "當前的日期是 %s" % i.day)
print ( "dd/mm/yyyy 格式是 %s/%s/%s" % (i.day, i.month, i.year) )
print ( "當前小時是 %s" % i.hour)
print ( "當前分鍾是 %s" % i.minute)
print ( "當前秒是 %s" % i.second)
|
Python處理時間和時間戳的內置模塊就有time
,和datetime
兩個,本文先說time
模塊。
關於時間戳的幾個概念
- 時間戳,根據1970年1月1日00:00:00開始按秒計算的偏移量。
- 時間元組(
struct_time
),包含9個元素。time.struct_time(tm_year=2017, tm_mon=10, tm_mday=1, tm_hour=14, tm_min=21, tm_sec=57, tm_wday=6, tm_yday=274, tm_isdst=0)
- 時間格式字符串,字符串形式的時間。
time
模塊與時間戳和時間相關的重要函數
time.time()
生成當前的時間戳,格式為10位整數的浮點數。time.strftime()
根據時間元組生成時間格式化字符串。time.strptime()
根據時間格式化字符串生成時間元組。time.strptime()
與time.strftime()
為互操作。time.localtime()
根據時間戳生成當前時區的時間元組。time.mktime()
根據時間元組生成時間戳。
示例
關於時間戳和格式化字符串的簡單示例如下
import time
#生成當前時間的時間戳,只有一個參數即時間戳的位數,默認為10位,輸入位數即生成相應位數的時間戳,比如可以生成常用的13位時間戳
def now_to_timestamp(digits = 10):
time_stamp = time.time()
digits = 10 ** (digits -10)
time_stamp = int(round(time_stamp*digits))
return time_stamp
#將時間戳規范為10位時間戳
def timestamp_to_timestamp10(time_stamp):
time_stamp = int (time_stamp* (10 ** (10-len(str(time_stamp)))))
return time_stamp
#將當前時間轉換為時間字符串,默認為2017-10-01 13:37:04格式
def now_to_date(format_string="%Y-%m-%d %H:%M:%S"):
time_stamp = int(time.time())
time_array = time.localtime(time_stamp)
str_date = time.strftime(format_string, time_array)
return str_date
#將10位時間戳轉換為時間字符串,默認為2017-10-01 13:37:04格式
def timestamp_to_date(time_stamp, format_string="%Y-%m-%d %H:%M:%S"):
time_array = time.localtime(time_stamp)
str_date = time.strftime(format_string, time_array)
return str_date
#將時間字符串轉換為10位時間戳,時間字符串默認為2017-10-01 13:37:04格式
def date_to_timestamp(date, format_string="%Y-%m-%d %H:%M:%S"):
time_array = time.strptime(date, format_string)
time_stamp = int(time.mktime(time_array))
return time_stamp
#不同時間格式字符串的轉換
def date_style_transfomation(date, format_string1="%Y-%m-%d %H:%M:%S",format_string2="%Y-%m-%d %H-%M-%S"):
time_array = time.strptime(date, format_string1)
str_date = time.strftime(format_string2, time_array)
實驗
print(now_to_date())
print(timestamp_to_date(1506816572))
print(date_to_timestamp('2017-10-01 08:09:32'))
print(timestamp_to_timestamp10(1506816572546))
print(date_style_transfomation('2017-10-01 08:09:32'))
結果為
1506836224000
2017-10-01 13:37:04
2017-10-01 08:09:32
1506816572
1506816572
2017-10-01 08-09-32
參考資料