python程式設計開發之日期操作例項分析

2022-09-28 02:42:13 字數 1668 閱讀 1912

在python中對日期進行操作的庫有:

import datetime

import time

對日期格式化資訊,可以參考官方api:

time.strftime

datetime

下面是我做的demo:

#datetime

import datetime

#當前日期

now = datetime.datetime.now程式設計客棧()

print(now.strftime('%y-%m-%d %h:%m:%s'))

print(now.strftime('%y-%m-%d'))

#string convert to datetime

time_str = '2013-07-29 01:05:00'

str_convert_2_time = datetime.datetime.strptime(time_str, '%y-%m-%d %h:%m:%s')

print(str_convert_2_time)

#比較兩個日期相差多少天

time_stra = '2013-07-29 01:05:00'

time_strb ='2013-08-29 01:05:00'

day = datetime.datetime.strptime(time_stra, '%y-%m-%d %h:%m:%s')

day2 = datetime.datetime.strptime(time_strb, '%y-%m-%d %h:%m:%s')

sub_day = day2 - day

print('和相差天'.format(time_程式設計客棧stra, time_strb, str(sub_day.days)))

#今後的n天的日期

n_days = 4

now = datetime.datetime.now()

my_date = datetime.timedelta(days=n_daucapdys)

n_day = now + my_date

print('從今天起的天的日期是:'.format(n_days))

print(n_day.strftime('%y-%m-%d %h:%m:%s'))

執行效果:

python 3.3.2 (v3.3.2:d047928ae3f6, may 16 2013, 00:03:43) [msc v.1600 32 bit (intel)] on win32

typucapde "copyright", "credits" or "license()" for more information.

>>> ******************************== restart ******************************==

>>>

2013-07-29 01:48:16

2013-07-29

2013-07-29 01:05:00

2013-07-29 01:05:00和2013-08-29 01:05:00相差31天

從今天起的4天的日期是:

2013-08-02 01:48:16

>>>

本文標題: python程式設計開發之日期操作例項分析

本文位址: /jiaoben/python/134999.html

Linux之日期操作

cat etc sysconfig clock 檢視時區 etc localtime 定義時區的檔案 序列化資料 usr share zoneinfo asia shanghai 正確的時區檔案 tzselect 生成時區檔案 cp usr share zoneinfo asia shanghai ...

Python之日期和時間

python 程式能用很多方式處理日期和時間,如time模組 calendar 模組可以用於格式化日期和時間 一 time模組 1 time.localtime 返回本地時間元組 a time.localtime print a 列印內容 time.struct time tm year 2020,...

Python之日期datetime模組的使用

python中包含了 datetime模組,它提供了非常強大的功能來處理日期和時間。datetime模組中,常用的物件和函式包括today,year,month,day,timedelta,strftime和strptime。首先匯入模組 from datetime import time,date...