天天看點

greenplum 查詢出來的數字加減日期_Python實踐代碼總結第5集(日期相關處理)

greenplum 查詢出來的數字加減日期_Python實踐代碼總結第5集(日期相關處理)
  1. 英文的月份轉數字及數字轉英文

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)加減一年

from

dateutil.relativedelta

import

relativedelta

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:

def

float_time(float_value):#datetime.fromtimestamp('1347334462').strftime('%Y-%m-%d')

return

datetime.datetime.fromtimestamp(float_value).strftime(

'%Y-%m-%d'

)

6.

string類型格式轉化為datetime格式

codes:

def

str_time(str_value=

'Fri Jan 18 11:00:05 +0800 2013'

):

from

datetime

import

datetime

import

calendar

print(str_value.split())

month = list(calendar.month_abbr).index(str_value.split()[1])

time_s = str_value.split()[3]

return

datetime.strptime(str_value.split()[-1]+

'-'

+str(month)+

'-'

+str_value.split()[2]+

'-'

+time_s,

'%Y-%m-%d-%H:%M:%S'

)

def

str_time(str_value=

'2013-01-18'

):

from

datetime

import

datetime

return

datetime.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()