Data science: How long did delivery take?

An order log has the time each order was placed and delivered. Measure the delivery times.

What to build

A program that computes delivery durations from timestamps.

Requirements

  • For each order (numbered from 1) print order K: H hours with one decimal, or order K: invalid if it was delivered before it was ordered.
  • Then, over the valid orders, print average: X hours (one decimal), late: L (more than 48 hours) and longest: order K (the first one if several are equal).

Input

Line 1: n. Then n lines ORDERED,DELIVERED, each time as YYYY-MM-DD HH:MM.

Output

n lines, then three summary lines.

Constraints

1 ≤ n ≤ 1000; at least one order is valid.

Example

Input:

3
2024-03-01 10:00,2024-03-02 16:30
2024-03-01 12:00,2024-03-04 12:00
2024-03-02 09:15,2024-03-02 21:45

Output:

order 1: 30.5 hours
order 2: 72.0 hours
order 3: 12.5 hours
average: 38.3 hours
late: 1
longest: order 2

Why it works

Real datetime values make the subtraction correct across days, months and leap years, and treating impossible durations as invalid keeps them from distorting the average.

Examples

Example 1 · Input
3
2024-03-01 10:00,2024-03-02 16:30
2024-03-01 12:00,2024-03-04 12:00
2024-03-02 09:15,2024-03-02 21:45
Expected output
order 1: 30.5 hours
order 2: 72.0 hours
order 3: 12.5 hours
average: 38.3 hours
late: 1
longest: order 2
Example 2 · Input
2
2024-05-01 08:00,2024-04-30 08:00
2024-05-01 08:00,2024-05-03 08:00
Expected output
order 1: invalid
order 2: 48.0 hours
average: 48.0 hours
late: 0
longest: order 2

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Subtract the two datetimes and use total_seconds() / 3600 for hours.

Hint 2

Keep invalid orders out of the average, the late count and the longest.

Solution

Show one correct solution (try it yourself first)
from datetime import datetime

FORMAT = "%Y-%m-%d %H:%M"
n = int(input())
valid = []
for k in range(1, n + 1):
    ordered, delivered = input().split(",")
    hours = (datetime.strptime(delivered, FORMAT) - datetime.strptime(ordered, FORMAT)).total_seconds() / 3600
    if hours < 0:
        print(f"order {k}: invalid")
    else:
        print(f"order {k}: {hours:.1f} hours")
        valid.append((k, hours))

durations = [h for _, h in valid]
longest = valid[0]
for k, h in valid:
    if h > longest[1]:
        longest = (k, h)
print(f"average: {sum(durations) / len(durations):.1f} hours")
print("late:", sum(1 for h in durations if h > 48))
print(f"longest: order {longest[0]}")

Lesson: Dates, times and text →