
- 英文的月份轉數字及數字轉英文
import calendar
# 數字轉月份的簡寫
calendar.month_abbr[12]--> 'Dec'
# 簡寫月份轉數字
list(calendar.month_abbr).index('Dec')--> 12
# 數字轉月份的全寫
calendar.month_name[12]--> 'December'
# 月份轉數字
list(calendar.month_name).index('December')--> 12
2.
年月日時分秒對應-->"%Y-%m-%d%H:%M:%S"3.
datetime日期加N天checking_date + datetime.timedelta(days=N), N可以是負數 表示減。
注意datetime格式指的是通過datetime.datetime.strptime(weibo_text_lst[1],
'%Y-%m-%d')獲得,但是 datetime.timedelta(days=N)中的datetime來源于import datetime.
例子:
import datetime
checking_date = datetime.datetime.strptime(weibo_text_lst[1],
'%Y-%m-%d')+ datetime.timedelta(days=1)
說明:
(1)可以把days改為hours minutes,就可以提前XX小時/分鐘了。
timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[,
hours[, weeks]]]]]]])
(2)加減一年
fromdateutil.relativedelta
importrelativedelta
checking_date = datetime.datetime.strptime(
'2028-09-19',
'%Y-%m-%d') +/- relativedelta(years=1)
4.
datetime日期比較大小datetime日期a和b直接比較, a>b是真的,傳回true;反之傳回false
4.1
datetime日期計算相差幾天/幾小時/幾秒等。(b-a).seconds #時間差的計算,機關為秒
#timedelta可以檢視:天數(days),秒數(seconds)等。
5.
float型數字轉化成datetime格式code:
deffloat_time(float_value):#datetime.fromtimestamp('1347334462').strftime('%Y-%m-%d')
returndatetime.datetime.fromtimestamp(float_value).strftime(
'%Y-%m-%d')
6.
string類型格式轉化為datetime格式codes:
defstr_time(str_value=
'Fri Jan 18 11:00:05 +0800 2013'):
fromdatetime
importdatetime
importcalendar
print(str_value.split())
month = list(calendar.month_abbr).index(str_value.split()[1])
time_s = str_value.split()[3]
returndatetime.strptime(str_value.split()[-1]+
'-'+str(month)+
'-'+str_value.split()[2]+
'-'+time_s,
'%Y-%m-%d-%H:%M:%S')
defstr_time(str_value=
'2013-01-18'):
fromdatetime
importdatetime
returndatetime.strptime(str_value,
'%Y-%m-%d')
說明:
(1)strptime(str,format),字元轉化成日期
7.
日期差datetime1 - datetime2獲得兩個datetime類型的日期差
8.
日期轉化成秒pub_time = datetime.datetime.strptime(ele[
'pub_time'],
'%m/%d/%Y')
pub_time_seconds = time.mktime(pub_time.timetuple())
9.
通過日期定位到一年的第幾個星期第幾天import datetime
(year, week_th, week_day) = datetime.datetime.strptime(time,
'%Y-%m-%d %H:%M:%S').isocalendar()