常見的日期格式操作總結 Python

2021-08-28 09:26:57 字數 1961 閱讀 1233

1. 字串轉換成日期格式:

from datetime import datetime

time_str =

'2016-09-10 4:23:21'

time = datetime.strptime(time_str,

'%y-%m-%d %h:%m:%s'

)# 根據字串本身的格式進行轉換

print

(time)

# 2016-09-10 04:23:21

time_str = time.strftime(

'%y-%m-%d %h:%m:%s'

)# 時間轉字串

print

(time_str)

# 2016-09-10 04:23:21

2. 把字串格式日期轉換成date格式(僅有日期沒有時間):
from datetime import datetime

time_str =

'2018-09-24'

time = datetime.strptime(time_str,

'%y-%m-%d'

)# 根據字串本身的格式進行轉換

date = time.date(

)# 只獲取日期,不含時間

print

(date)

3. 獲取乙個日期的前幾天:

timedaltedatetime中的乙個物件,該物件表示兩個時間的差值。具體引數:

datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

from datetime import datetime, timedelta

print

(datetime.now(

)- timedelta(seconds=5*

60))# 當前時間前 5 分鐘

print

(datetime.now(

)+ timedelta(hours=20*

24))# 當前時間後 20 天

4. 把字串轉換成時間戳型別:
import time

date =

'2018-09-24'

time1 = time.mktime(time.strptime(date+

' 09:00:00'

,'%y-%m-%d %h:%m:%s'))

print

(time1)

# 1537750800.0

time2 = time.mktime(time.strptime(date+

' 17:00:00'

,'%y-%m-%d %h:%m:%s'))

print

(time2)

# 1537779600.0

5. 獲取某一日是當前年的第幾天:
import datetime

y =int

(input()

)# 年

m =int

(input()

)# 月

d =int

(input()

)# 日

targetday = datetime.date(y, m, d)

# 將輸入的日期格式化成標準的日期

daycount = targetday - datetime.date(targetday.year -1,

12,31)

# 減去上一年最後一天

print

(daycount.days)

宣告:總結學習,有問題可以批評指正,大神可以略過哦

JS 常見的日期格式處理

var now new date 當前日期 var nowdayofweek now.getday 1 今天本週的第幾天 var nowday now.getdate 當前日 var nowmonth now.getmonth 當前月 var nowyear now.getfullyear 當前年 ...

SQL日期格式操作

sql server中文版的預設的日期欄位datetime格式是yyyy mm dd thh mm ss.mmm 例如 select getdate 2004 09 12 11 06 08.177 整理了一下sql server裡面可能經常會用到的日期格式轉換方法 舉例如下 select conve...

js 日期格式操作

擴充套件date的format方法 date.prototype.format function format if y test format for var k in o return format 轉換日期物件為日期字串 param date 日期物件 param isfull 是否為完整的日...