python時間計算_日期天數差計算(Python)

描述

從json文件中讀取兩個時間數據(數據格式例如:2019.01.01,數據類型是字符串),并計算結果,打印出兩個時間間隔了多少天。

輸入/輸出描述

輸入描述

json文件名稱datetime.json,格式如下:

{

"day1": "1949.10.01",

"day2": "2019.04.25"

}

輸出描述

控制臺打印兩個時間(day1和day2)間隔了多少天。

25408

解決思路

讀取json文件中的數據后解析有用的部分,并做校驗(檢查格式是否正確)。在日期格式正確的情況下將日期轉換為datetime.date,并做計算。最后輸出結果。

代碼

"""

時間差計算。

從json文件中讀取兩個時間數據,計算并打印兩個時間間隔了多少天。

"""

import datetime

import json

import traceback

class TimeFormatError(Exception):

def __init__(self, message):

self.message = "TimeFormatError: " + message

def days_compute(times):

"""

Calculated date interval.

:param times: time dictionary

:return: date interval

"""

time1 = times["day1"]

time2 = times["day2"]

if time1.count(".") < 2:

raise TimeFormatError("Time format(yyyy.mm.dd) error. %s" % time1)

if time2.count(".") < 2:

raise TimeFormatError("Time format(yyyy.mm.dd) error. %s" % time2)

date1 = parse(time1)

date2 = parse(time2)

return (date2 - date1).days

def parse(time_str):

"""

Parse time format.

:param time_str: time string

:return: date

"""

time_list = time_str.split(".")

year = time_list[0]

month = time_list[1]

day = time_list[2]

return datetime.date(int(year), int(month), int(day))

def read_json_file(path):

"""

Read json file.

:param path: json file url

:return: json file data

"""

with open(path, "r") as json_file:

data = json.load(json_file)

json_file.close()

return data

# main method

url = "datetimes.json"

try:

base = read_json_file(url)

day = days_compute(base)

print(day)

except TimeFormatError as e:

print(str(e))

print("errmsg:\n%s" % traceback.format_exc())

except Exception as e:

print(str(e))

print("errmsg:\n%s" % traceback.format_exc())

代碼走讀

import datetime

import json

import traceback

# 自定義異常類型TimeFormatError, 用于在代碼中校驗錯誤時間格式時拋出

class TimeFormatError(Exception):

def __init__(self, message):

self.message = "TimeFormatError: " + message

# 定義計算日期差的函數

def days_compute(times):

"""

Calculated date interval.

:param times: time dictionary

:return: date interval

"""

# 從字典中獲取兩個時間日期

time1 = times["day1"]

time2 = times["day2"]

# 日期格式校驗,如果日期格式錯誤(例如“2019.10”),拋出TimeFormatError

if time1.count(".") < 2:

raise TimeFormatError("Time format(yyyy.mm.dd) error. %s" % time1)

if time2.count(".") < 2:

raise TimeFormatError("Time format(yyyy.mm.dd) error. %s" % time2)

# 在這里調用自定義的parse函數,將兩個日期時間格式由字符串轉換為datetime.date格式

date1 = parse(time1)

date2 = parse(time2)

# 返回計算結果(整型)

return (date2 - date1).days

# 解析時間字符串,轉換為datetime.date格式

def parse(time_str):

"""

Parse time format.

:param time_str: time string

:return: date

"""

# 使用split()函數將字符串轉化為列表,并分解出年月日

time_list = time_str.split(".")

year = time_list[0]

month = time_list[1]

day = time_list[2]

# 將日期轉換為datetime.date格式并返回

return datetime.date(int(year), int(month), int(day))

# 讀取json文件的信息,將json文件轉化為字典格式

def read_json_file(path):

"""

Read json file.

:param path: json file url

:return: json file data

"""

with open(path, "r") as json_file:

data = json.load(json_file)

json_file.close()

return data

# main method

# 代碼開始執行的地方

# json文件的url

url = "datetimes.json"

try:

# 調用自定義的read_json_file函數獲取json文件的內容

base = read_json_file(url)

# 計算結果,并打印輸出

day = days_compute(base)

print(day)

# 捕獲異常,打印錯誤信息和堆棧

except TimeFormatError as e:

print(str(e))

print("errmsg:\n%s" % traceback.format_exc())

except Exception as e:

print(str(e))

print("errmsg:\n%s" % traceback.format_exc())

傳送門

1. count()函數

2. split()方法

3. int()函數

4. print()函數

5. str()函數

測試用例

1. json文件中日期格式正常:

json格式如下:

{

"day1": "1949.10.01",

"day2": "2019.04.25"

}

python腳本執行結果:

25408

即1949年10月1日與2019年4月25日間隔了25408天。

2. json文件中只有年和月,沒有日(day)

json文件如下:

{

"day1": "1949.10",

"day2": "2019.04.25"

}

python腳本執行如下:可以看出程序拋出并捕獲了自定義異常TimeFormatError,并將其錯誤堆棧打出。

Time format(yyyy.mm.dd) error. 1949.10

errmsg:

Traceback (most recent call last):

File "/Users/Desktop/Python Apps/untitled_test/day_compute.py", line 67, in

day = days_compute(base)

File "/Users/Desktop/Python Apps/untitled_test/day_compute.py", line 25, in days_compute

raise TimeFormatError("Time format(yyyy.mm.dd) error. %s" % time1)

TimeFormatError: Time format(yyyy.mm.dd) error. 1949.10

3. 日期錯誤。

日期錯誤。例如輸入的是1000年13月1日(當然不存在這個日期)。

json文件如下:

{

"day1": "1000.13.1",

"day2": "2019.04.25"

}

python執行結果如下:

month must be in 1..12

errmsg:

Traceback (most recent call last):

File "/Users/Desktop/Python Apps/untitled_test/day_compute.py", line 67, in

day = days_compute(base)

File "/Users/Desktop/Python Apps/untitled_test/day_compute.py", line 29, in days_compute

date1 = parse(time1)

File "/Users/Desktop/Python Apps/untitled_test/day_compute.py", line 46, in parse

return datetime.date(int(year), int(month), int(day))

ValueError: month must be in 1..12

代碼捕獲到python內置異常ValueError(46行的parse函數內所拋出),指出日期有誤。

標簽:return,Python,天數,json,日期,file,time,day,TimeFormatError

來源: https://blog.csdn.net/TCatTime/article/details/89838237

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/394753.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/394753.shtml
英文地址,請注明出處:http://en.pswp.cn/news/394753.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

c語言編常見算法,5個常見C語言算法

5個常見C語言算法十進制轉換為二進制的遞歸程序字符串逆置的遞歸程序整數數位反序&#xff0c;例如12345->54321四舍五入程序(考慮正負數)二分法查找的遞歸函數#include#include#include//十進制轉換為二進制的遞歸程序voidDecimalToBinary(int n){if(n<0){printf("…

利用Kinect將投影變得可直接用手操控

Finally 總算是到了這一天了&#xff01;假期里算法想不出來&#xff0c;或者被BUG折磨得死去活來的時候&#xff0c;總是YY著什么時候能心情愉快地坐在電腦前寫一篇項目總結&#xff0c;今天總算是抽出時間來總結一下這神奇的幾個月。 現在回過頭來看&#xff0c;上學期退出AC…

my-medium.cnf_您的手機如何打開medium.com-我將讓門衛和圖書管理員解釋。

my-medium.cnfby Andrea Zanin由Andrea Zanin 您的手機如何打開medium.com-我將讓門衛和圖書管理員解釋。 (How your phone opens medium.com — I’ll let a doorman and a librarian explain.) Hey did you notice what just happened? You clicked a link, and now here y…

springboot自動配置的原理_SpringBoot自動配置原理

SpringBoot的啟動入口就是一個非常簡單的run方法&#xff0c;這個run方法會加載一個應用所需要的所有資源和配置&#xff0c;最后啟動應用。通過查看run方法的源碼&#xff0c;我們發現&#xff0c;run方法首先啟動了一個監聽器&#xff0c;然后創建了一個應用上下文Configurab…

Django first lesson 環境搭建

pycharm ide集成開發環境 &#xff08;提高開發效率&#xff09; 解釋器/編譯器編輯器調試環境虛擬機連接 設置VirtualBox端口 操作1 操作2 點擊號添加&#xff0c;名稱為SSH&#xff0c;其中主機端口為物理機的端口&#xff0c;這里設置為1234&#xff0c;子系統端口為虛擬機的…

《Drupal實戰》——3.3 使用Views創建列表

3.3 使用Views創建列表 我們接著講解Views的設置&#xff0c;首先做一個簡單的實例。 3.3.1 添加內容類型“站內公告” 添加一個內容類型“站內公告”&#xff0c;屬性配置如表3-1所示。 為該內容類型設置Pathauto的模式news/[node:nid]&#xff0c;并且我們在這里將節點類型…

c語言函數編正切余切運算,淺談正切函數與余切函數的應用

九年義務教育三年制初級中學“數學”課本中&#xff0c;對正切函數和余切函數的定義是這樣下的&#xff1a;在&#xff32;&#xff54;&#xff21;&#xff22;&#xff23;中&#xff0c;∠&#xff23;&#xff1d;&#xff19;&#xff10;&#xff0c;&#xff41;&#…

wget命令下載文件

wget -r -N -l -k http://192.168.99.81:8000/solrhome/ 命令格式&#xff1a; wget [參數列表] [目標軟件、網頁的網址] -V,–version 顯示軟件版本號然后退出&#xff1b; -h,–help顯示軟件幫助信息&#xff1b; -e,–executeCOMMAND 執行一個 “.wgetrc”命令 -o,–output…

idea mybatis generator插件_SpringBoot+MyBatis+Druid整合demo

最近自己寫了一個SpringBootMybatis(generator)druid的demo1. mybatisgenerator逆向工程生成代碼1. pom文件pom文件添加如下內容&#xff0c;引入generator插件org.mybatis.generator mybatis-generator-maven-plugin 1.3.5 mysql …

vr格式視頻價格_如何以100美元的價格打造自己的VR耳機

vr格式視頻價格by Maxime Coutte馬克西姆庫特(Maxime Coutte) 如何以100美元的價格打造自己的VR耳機 (How you can build your own VR headset for $100) My name is Maxime Peroumal. I’m 16 and I built my own VR headset with my best friends, Jonas Ceccon and Gabriel…

python_裝飾器

# 裝飾器形成的過程 : 最簡單的裝飾器 有返回值得 有一個參數 萬能參數# 裝飾器的作用# 原則 &#xff1a;開放封閉原則# 語法糖&#xff1a;裝飾函數名# 裝飾器的固定模式 import time # time.time() # 獲取當前時間 # time.sleep() # 等待 # 裝飾帶參數的裝飾器 def timer…

歐洲的數據中心與美國的數據中心如何區分?

人會想到這意味著&#xff0c;在歐洲和北美的數據中心的設計基本上不會有大的差異。不過&#xff0c;一些小的差異是確實存在的。您可能想知道為什么你需要了解歐洲和北美的數據中心之間的差異&#xff0c;這對你的公司有幫助嗎?一個設計團隊往往能從另一個設計團隊那里學到東…

老農過河

java老農過河問題解決 http://www.52pojie.cn/thread-550328-1-1.html http://bbs.itheima.com/thread-141470-1-1.html http://touch-2011.iteye.com/blog/1104628 轉載于:https://www.cnblogs.com/wangjunwei/p/6032602.html

python isalnum函數_探究Python中isalnum()方法的使用

探究Python中isalnum()方法的使用 isalnum()方法檢查判斷字符串是否包含字母數字字符。 語法 以下是isalnum()方法的語法&#xff1a; str.isa1num() 參數 NA 返回值 如果字符串中的所有字符字母數字和至少有一個字符此方法返回 true&#xff0c;否則返回false。 例子 下面的例…

docker快速入門_Docker標簽快速入門

docker快速入門by Shubheksha通過Shubheksha Docker標簽快速入門 (A quick introduction to Docker tags) If you’ve worked with Docker even for a little while, I bet you’ve come across tags. They often look like “my_image_name:1” where the part after the col…

動態規劃算法——最長上升子序列

今天我們要講的是最長上升子序列&#xff08;LIS&#xff09;。【題目描述】給定N個數&#xff0c;求這N個數的最長上升子序列的長度。【樣例輸入】      【樣例輸出】7        42 5 3 4 1 7 6那么什么是最長上升子序列呢&#xff1f; 就是給你一個序列…

如何快速掌握一門新技術/語言/框架

IT行業中的企業特點是都屬于知識密集型企業。這種企業的核心競爭力與員工的知識和技能密切相關。而如果你在企業中扮演的是工程師的角色的話&#xff0c;那么 你的核心競爭力就是IT相關的知識與技能的儲備情況。而眾所周知&#xff0c;IT行業是一個大量產生新知識的地方&#x…

c語言今天星期幾問題,C語言輸入今天星期幾

滿意答案迷茫03222015.07.24采納率&#xff1a;55% 等級&#xff1a;9已幫助&#xff1a;665人123456789101112131415161718192021#include<stdio.h>int main(void){ enum weekday{ sun, mon, tue, wed, thu, fri, sat }; int n; printf("輸入星期數(0-…

備忘錄模式 詳解

定義 在不破壞封裝性的前提下&#xff0c;捕獲一個對象的內部狀態&#xff0c;并在該對象之外保存這個狀態&#xff1b; 行為型模式 角色 發起人角色&#xff08;Originator&#xff09;&#xff1a;記錄當前時刻的內部狀態&#xff0c;負責定義哪些屬于備份范圍的狀態&#xf…

dll oem證書導入工具_技術干貨 | 惡意代碼分析之反射型DLL注入

歡迎各位添加微信號&#xff1a;qinchang_198231 加入安全 交流群 和大佬們一起交流安全技術01技術概要這是一種允許攻擊者從內存而非磁盤向指定進程注入DLL的技術&#xff0c;該技術比常規的DLL注入更為隱蔽&#xff0c;因為除了不需要磁盤上的實際DLL文件之外&#xff0c;它…