describe
Read two time data (data format for example: 2019.01.01, data type is string) from the json file, and calculate the result, and print out the number of days between the two times.
I / O description
Input description
The JSON file name is datetime.json. The format is as follows:
{ "day1": "1949.10.01", "day2": "2019.04.25" }
Output description
How many days did the console print between the two times (day1 and day2).
25408
Solutions
After reading the data in the json file, parse the useful parts and check (check whether the format is correct). When the date format is correct, convert the date to datetime.date and calculate it. Finally output the result.
Code
""" //Time difference calculation. //Read two time data from the json file, calculate and print how many days between the two times. """ 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: <dict> time dictionary :return: <int> 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: <str> time string :return: <datetime.date> 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: <str> json file url :return: <dict> 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())
Code review
import datetime import json import traceback # Custom exception type timeformatererror, used to throw when verifying the error time format in the code class TimeFormatError(Exception): def __init__(self, message): self.message = "TimeFormatError: " + message # Define a function to calculate the date difference def days_compute(times): """ Calculated date interval. :param times: <dict> time dictionary :return: <int> date interval """ # Get two time dates from the dictionary time1 = times["day1"] time2 = times["day2"] # Check the date format. If the date format is wrong (for example, "2019.10"), throw timeformatererror 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) # Call the custom parse function here to convert the two date time formats from string to datetime.date format date1 = parse(time1) date2 = parse(time2) # Return calculation result (integer) return (date2 - date1).days # Parse time string, convert to datetime.date format def parse(time_str): """ Parse time format. :param time_str: <str> time string :return: <datetime.date> date """ # Use the split() function to convert the string into a list and decompose the date time_list = time_str.split(".") year = time_list[0] month = time_list[1] day = time_list[2] # Convert date to datetime.date format and return return datetime.date(int(year), int(month), int(day)) # Read the information of json file and convert it to dictionary format def read_json_file(path): """ Read json file. :param path: <str> json file url :return: <dict> json file data """ with open(path, "r") as json_file: data = json.load(json_file) json_file.close() return data # main method # Where the code starts executing # The url of the json file url = "datetimes.json" try: # Call the custom read json file function to get the contents of the json file base = read_json_file(url) # Calculate the result and print it out day = days_compute(base) print(day) # Catch exceptions, print error messages and stacks 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())