Python日期 時間的使用

Python日期 時間的使用

時間格式

在Python中,通常有這幾種方式來表示時間:1)時間戳; 2)格式化的時間字符串; 3)元組(struct_time)共九個元素。

1)時間戳(timestamp)的方式:

通常來說,時間戳表示的是從1970年1月1日00:00:00開始按秒計算的偏移量。我們運行“type(time.time())”,返回的是float類型。返回時間戳方式的函數主要有time(),clock()等。

2)格式化的時間字符串,比如"%Y-%m-%d %H:%M:%S"

3)元組(struct_time)方式:

struct_time元組共有9個元素,返回struct_time的函數主要有gmtime(),localtime(),strptime()。下面列出這種方式元組中的幾個元素:

struct_time(tm_year=2016, tm_mon=2, tm_mday=2, tm_hour=11, tm_min=16, tm_sec=43, tm_wday=1, tm_yday=33, tm_isdst=0)

年,月,日,時,分,秒,星期幾(0-6),年的第幾天,是否夏令時(默認爲-1)

接着介紹time模塊中常用的幾個函數:

1)time.localtime([secs]):將一個時間戳轉換爲當前時區的struct_time。secs參數未提供,則以當前時間爲準。

2)time.gmtime([secs]):和localtime()方法類似,gmtime()方法是將一個時間戳轉換爲UTC時區(0時區)的struct_time。

3)time.time():返回當前時間的時間戳。

4)time.mktime(t):將一個struct_time轉化爲時間戳。

5)time.sleep(secs):線程推遲指定的時間運行。單位爲秒。

6)time.clock():這個需要注意,在不同的系統上含義不同。在UNIX系統上,它返回的是“進程時間”,它是用秒錶示的浮點數(時間戳)。而在WINDOWS中,第一次調用,返回的是進程運行的實際時間。而第二次之後的調用是自第一次調用以後到現在的運行時間。(實際上是以WIN32上QueryPerformanceCounter()爲基礎,它比毫秒錶示更爲精確)

7)time.asctime([t]):把一個表示時間的元組或者struct_time表示爲這種形式:‘Sun Jun 20 23:21:05 1993’。如果沒有參數,將會將time.localtime()作爲參數傳入。

8)time.ctime([secs]):把一個時間戳(按秒計算的浮點數)轉化爲time.asctime()的形式。如果參數未給或者爲None的時候,將會默認time.time()爲參數。它的作用相當於time.asctime(time.localtime(secs))。

9)time.strftime(format[, t]):把一個代表時間的元組或者struct_time(如由time.localtime()和time.gmtime()返回)轉化爲格式化的時間字符串。如果t未指定,將傳入time.localtime()。如果元組中任何一個元素越界,ValueError的錯誤將會被拋出。

10)time.strptime(string[, format]):把一個格式化時間字符串轉化爲struct_time。實際上它和strftime()是逆操作。在這個函數中,format默認爲:"%a %b %d %H:%M:%S %Y"。

最後,對time模塊進行一個總結。根據之前描述,在Python中共有三種表達方式:1)timestamp 2)tuple或者struct_time 3)格式化字符串。

1、使用datetime模塊來獲取當前的日期和時間

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)
當前的日期和時間是 2016-02-01 17:19:16.102793
ISO格式的日期和時間是 2016-02-01T17:19:16.102793
當前的年份是 2016
當前的月份是 2
當前的日期是  1
dd/mm/yyyy 格式是  1/2/2016
當前小時是 17
當前分鐘是 19
當前秒是  16

2、使用time模塊來獲取當前的時間和日期

import time
print (time.strftime("%H:%M:%S"))
## 12 hour format ##
print (time.strftime("%I:%M:%S"))
# 日期
print (time.strftime("%d/%m/%Y"))
print time.localtime()
17:39:03
05:39:03
01/02/2016
time.struct_time(tm_year=2016, tm_mon=2, tm_mday=1, tm_hour=17, tm_min=39, tm_sec=3, tm_wday=0, tm_yday=32, tm_isdst=0)

3、獲取當前時間並轉換爲指定日期格式

import datetime
#獲得當前時間
now = datetime.datetime.now() # ->這是時間數組格式
print now
#轉換爲指定的格式:
otherStyleTime = now.strftime("%Y-%m-%d %H:%M:%S")
print otherStyleTime
print now.strftime("%Y-%m-%d")
2016-02-01 17:39:42.062818
2016-02-01 17:39:42
2016-02-01

4、字符串格式轉化

如a = “2013-10-10 23:40:00”,想改爲 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)
otherStyleTime
'2013/10/10 23:40:00'

5、時間和時間戳之間的相互轉化

#日期到時間戳上的轉換:
import datetime
import time
t = datetime.datetime(2014,12, 6, 12, 10, 10)
timestamp = time.mktime(t.timetuple())
print timestamp
1417839010.0
#時間戳到時間日期的轉換:
import datetime 
import time
t = time.localtime(timestamp)
timeStr = time.strftime('%Y-%m-%d %H:%M:%S', t)
print timeStr
2014-12-06 12:10:10

6、時間戳轉換爲指定格式日期

利用localtime()轉換爲時間數組,然後格式化爲需要的格式,如:

timeStamp = 1381419600
timeArray = time.localtime(timeStamp)
otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
otherStyleTime
'2013-10-10 23:40:00'
timeStamp = 1381419600
dateArray = datetime.datetime.utcfromtimestamp(timeStamp)
otherStyleTime = dateArray.strftime("%Y-%m-%d %H:%M:%S")
otherStyleTime
'2013-10-10 15:40:00'

7、獲得三天前的時間的方法

import time
import datetime
#先獲得時間數組格式的日期
threeDayAgo = (datetime.datetime.now() - datetime.timedelta(days = 3))
#轉換爲時間戳:
timeStamp = int(time.mktime(threeDayAgo.timetuple()))
#轉換爲其他字符串格式:
otherStyleTime = threeDayAgo.strftime("%Y-%m-%d %H:%M:%S")
otherStyleTime
'2016-01-30 12:25:08'

8、給定時間戳,計算該時間的幾天前時間

timeStamp = 1381419600
#先轉換爲datetime
import datetime
import time
dateArray = datetime.datetime.utcfromtimestamp(timeStamp)
threeDayAgo = dateArray - datetime.timedelta(days = 3)
threeDayAgo
datetime.datetime(2013, 10, 7, 15, 40)

9、計算昨天和明天的日期

import datetime #導入日期時間模塊
today = datetime.date.today() #獲得今天的日期
print today #輸出今天日期
yesterday = today - datetime.timedelta(days=1) #用今天日期減掉時間差,參數爲1天,獲得昨天的日期
print yesterday
tomorrow = today + datetime.timedelta(days=1) #用今天日期加上時間差,參數爲1天,獲得明天的日期
print tomorrow
print "昨天:%s, 今天:%s, 明天:%s" % (yesterday, today, tomorrow) #字符串拼接在一起輸出,這3天的日期
2016-02-02
2016-02-01
2016-02-03
昨天:2016-02-01, 今天:2016-02-02, 明天:2016-02-03

10、獲取歷史交易日

歷史交易日往往因爲法定節假日的不固定而導致交易日不固定,給我們的回測帶來了很大不便,這裏提供一個簡單方法,通過獲取某隻股票歷史的交易日獲得。

import time
initial = '2005-01-05'
tradingdays = get_price('000423.XSHE', fields='price', start_date=initial, 
                            end_date=time.strftime('%Y-%m-%d', time.localtime()))
tradingdays.index
DatetimeIndex(['2005-01-05', '2005-01-06', '2005-01-07', '2005-01-10',
               '2005-01-11', '2005-01-12', '2005-01-13', '2005-01-14',
               '2005-01-17', '2005-01-18', 
               ...
               '2016-01-19', '2016-01-20', '2016-01-21', '2016-01-22',
               '2016-01-25', '2016-01-26', '2016-01-27', '2016-01-28',
               '2016-01-29', '2016-02-01'],
              dtype='datetime64[ns]', length=2691, freq=None, tz=None)
start = '2015-06-01'
end = '2015-08-01'
days = tradingdays[start:end].index
days
DatetimeIndex(['2015-06-01', '2015-06-02', '2015-06-03', '2015-06-04',
               '2015-06-05', '2015-06-08', '2015-06-09', '2015-06-10',
               '2015-06-11', '2015-06-12', '2015-06-15', '2015-06-16',
               '2015-06-17', '2015-06-18', '2015-06-19', '2015-06-23',
               '2015-06-24', '2015-06-25', '2015-06-26', '2015-06-29',
               '2015-06-30', '2015-07-01', '2015-07-02', '2015-07-03',
               '2015-07-06', '2015-07-07', '2015-07-08', '2015-07-09',
               '2015-07-10', '2015-07-13', '2015-07-14', '2015-07-15',
               '2015-07-16', '2015-07-17', '2015-07-20', '2015-07-21',
               '2015-07-22', '2015-07-23', '2015-07-24', '2015-07-27',
               '2015-07-28', '2015-07-29', '2015-07-30', '2015-07-31'],
              dtype='datetime64[ns]', freq=None, tz=None)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章