Python中用datetime包進行對時間的一些操做

1. 計算給出兩個時間之間的時間差

import datetime as dt
# current time
cur_time = dt.datetime.today()
# one day
pre_time = dt.date(2016, 5, 20) # eg: 2016.5.20
delta = cur_time - pre_time
# if you want to get discrepancy in days
print delta.days
# if you want to get discrepancy in hours
print delta.hours
# and so on

2. 獲取n天前的時間

cur_time = dt.now()
# previous n days
pre_time = dt.timedelta(days=n)

3. 將給定的時間精確到天或者其餘單位

cur_time = dt.now()
# get day of current time
cur_day = cur_time.replace(hour=0, minute=0, second=0, mircrosecond=0)

4. 獲取一連串的時間序列(返回list)

cur_time = dt.datetime.today()
datelist = [cur_time - dt.timedelta(days=x) for x in range(0, 100)]

或者html

import pandas as pd
datelist =  pd.date_range(pd.datetime.today(), periods=100).tolist()

5. 將時間字符串轉化爲datetime類型

date_formate = "%Y-%m-%d" # year-month-day
time = dt.strptime('2016-06-22', date_format)

6. 將時間類型轉化爲字符串類型

time_str = dt.strftime("%Y-%m-%d", dt.now()) # return like "2016-06-22"

參考:

https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
http://stackoverflow.com/questions/993358/creating-a-range-of-dates-in-python
http://stackoverflow.com/questions/151199/how-do-i-calculate-number-of-days-betwen-two-dates-using-python
http://stackoverflow.com/questions/3183707/stripping-off-the-seconds-in-datetime-pythonpython

相關文章
相關標籤/搜索