python日期操作

2021-09-20 07:50:22 字數 2318 閱讀 1632

python日期操作用到庫time, datetime

格式化字串含義:

%a abbreviated weekday name 本地化星期縮略格式

%a full weekday name 本地化星期完整格式

%b abbreviated month name 本地化月份縮略格式

%b full month name 本地化月份完整格式

%d day of month as decimal number (01 - 31) 月份內日期索引

%h hour in 24-hour format (00 - 23) 24小時索引

%i hour in 12-hour format (01 - 12) 12小時索引

%j day of year as decimal number (001 - 366) 年內日期索引

%m month as decimal number (01 - 12) 月份索引

%m minute as decimal number (00 - 59) 分鐘索引

%p current locale's a.m./p.m. indicator for 12-hour clock 本地化上午/下午指示符

%s second as decimal number (00 - 59) 秒索引

%u week of year as decimal number, with sunday as first day of week (00 - 51) 年內星期索引, 以週日為一周開始

%w weekday as decimal number (0 - 6; sunday is 0) 週內星期索引,週日為0

%w week of year as decimal number, with monday as first day of week (00 - 51) 年內星期索引, 以周一為一周開始

%x date representation for current locale 本地化日期表示

%x time representation for current locale 本地化時間表示

%y year without century, as decimal number (00 - 99) 世紀內年份索引, 即相當於兩位年份表示

%y year with century, as decimal number 帶世紀值年份索引

%z, %z time-zone name or abbreviation; no characters if time zone is unknown 時區名稱或縮寫, 未知時為空

%% percent sign 百分號轉義

示例**1(python 3):

# coding=utf-8

import time, datetime

# strftime(string)函式用於返回格式化日期字串

# 格式化當前日期

now = datetime.datetime.now().strftime('%b-%d-%y %h:%m:%s')

print(now)

# strptime(string, string)函式用於返回由特定格式解析得到的日期物件

nowobj = datetime.datetime.strptime('15-sep-21 16:34', '%y-%b-%d %h:%m')

print(nowobj)

print(nowobj.strftime('%b-%d-%y %h:%m'))

輸出結果:

dec-11-15 11:33:23

2015-09-21 16:34:00

sep-21-2015 16:34

示例**2

import time, datetime

startdate = datetime.datetime.strptime('20150916', '%y%m%d')

enddate = datetime.datetime.strptime('20150921', '%y%m%d')

oneday=datetime.timedelta(days=1)

while startdate != enddate:

print(startdate.strftime('%y%m%d'))

startdate += oneday

輸出結果:

20150917

20150918

20150919

20150920

Python日期操作

1.日期輸出格式化 所有日期 時間的api都在datetime模組內。1.datetime string now datetime.datetime.now now.strftime y m d h m s 輸出2012 03 05 16 26 23.870105 strftime是datetime...

python日期操作

python日期操作用到庫time,datetime 格式化字串含義 a abbreviated weekday name 本地化星期縮略格式 a full weekday name 本地化星期完整格式 b abbreviated month name 本地化月份縮略格式 b full month ...

python 日期操作

time.mktime time.strptime 2018 02 12 y m d 1518364800.0 time.strftime y m d time.localtime 1518364800 2018 02 11 time.strftime y m d h m s time.localt...