본문 바로가기
데이터분석과 AI/빅데이터 분석기사

[빅데이터분석기사 실기][작업형1] 시간 데이터 다루기(datetime, timedelta)

by 우공80 2023. 7. 3.
728x90

시간 데이터 다루기

 

 

제6회 빅데이터분석기사 실기 시험 첫 번째 문제로 datetime과 timedelta를 다루는 문제가 나왔습니다.

후기를 보면 이 문제에서 고생한 사람들이 많고, 저 또한 많은 시간을 소모했기에 정리해 둡니다.

 

1. datetime과 timedelta의 차이

'datetime' 클래스는 날짜 및 시간 정보를 모두 포함하여 특정 시점을 나타냅니다. 날짜와 시간을 전체적으로 작업하는 데 사용되며 특정 구성 요소(년, 월, 일, 시, 분 등) 추출과 같은 다양한 작업을 수행할 수 있습니다.

 

timedelta 클래스는 두 datetime 개체 간의 기간 또는 차이를 나타냅니다. 특정 시간을 더하거나 빼는 등 'datetime' 객체에 대한 산술 연산을 수행하는 데 사용됩니다. datetime객체 - datetime객체 연산을 하면 timedelta가 됩니다.

 

따라서 datetime객체 + timedelta객체 = datetime객체로도 연산이 가능합니다.

 

기본적인 연산에 대한 예제는 다음과 같습니다.

 

(1) datetime 객체 생성 및 시간의 구성요소 추출, string을 datetime으로 변경

from datetime import datetime

# Create a datetime object
dt = datetime(2023, 7, 1, 10, 30, 0)

# Access components of the datetime object
print(dt.year)     # Output: 2023
print(dt.month)    # Output: 7
print(dt.day)      # Output: 1
print(dt.hour)     # Output: 10
print(dt.minute)   # Output: 30
print(dt.second)   # Output: 0

# Convert string to datetime objects
dt2='2023-07-01 10:30:00'
dt2=datetime.strptime(dt2, "%Y-%m-%d %H:%M:%S")
print(type(dt2)) # Output: <class 'datetime.datetime'>

(1) timedelta 객체 생성 및 datetime과 timedelta 연산

from datetime import datetime, timedelta

# Create two datetime objects
start = datetime(2023, 7, 1, 10, 30, 0)
end = datetime(2023, 7, 2, 11, 0, 0)

# Calculate the time difference
diff = end - start

# Print the time difference
print(diff)   # Output: 0:30:00

print(diff.seconds)  #Output: 1800
print(diff.seconds/60)  #Output: 30.0
print(diff.days)  #Output: 30.0

# Create a timedelta object representing 1 hour
one_hour = timedelta(hours=1)

# Add the timedelta to the start datetime
new_time = start + one_hour

# Print the new time
print(new_time)   # Output: 2023-07-01 11:30:00

timedelta는 seconds와 days만 추출이 가능합니다. 시간이나 분으로 변환하기 위해서는 seconds를 이용해 계산이 필요합니다.

2. 기출문제 응용

시험에서는 소방서의 평균 출동시간이 가장 긴 곳의 출동시간을 분으로 구하는 문제가 나왔습니다.

 

비슷하게 문제를 구성해 보았습니다. 아래와 같이 주어진 데이터에서 접수시간의 년, 월, 일을 추출하고, 접수시간과 출동시간의 차이를 분으로 구해보았습니다. 찾아보다 보니, 달의 이름과 요일을 string으로 반환하는 함수도 있어서 추가하였습니다. 

import pandas as pd
from datetime import datetime, timedelta

# Example data for reception and dispatch times
data = {
    'Reception Time': [
        "2023-06-30 10:30:00",
        "2022-12-15 11:00:00",
        "2023-02-28 11:30:00",
        "2024-09-01 12:00:00",
        "2023-11-10 12:30:00",
        "2022-07-20 13:00:00",
        "2023-04-05 13:30:00",
        "2022-10-11 14:00:00",
        "2024-03-22 14:30:00",
        "2023-08-02 15:00:00"
    ],
    'Dispatch Time': [
        "2023-06-30 11:41:00",
        "2022-12-15 12:12:00",
        "2023-02-28 12:43:00",
        "2024-09-01 13:14:00",
        "2023-11-10 13:45:00",
        "2022-07-20 14:06:00",
        "2023-04-05 14:47:00",
        "2022-10-11 15:18:00",
        "2024-03-22 15:49:00",
        "2023-08-02 16:10:00"
    ]
}

# Create dataframe
df = pd.DataFrame(data)

# Convert reception time and dispatch time to datetime format
df['Reception Time'] = df['Reception Time'].apply(lambda x: datetime.strptime(x, "%Y-%m-%d %H:%M:%S"))
df['Dispatch Time'] = df['Dispatch Time'].apply(lambda x: datetime.strptime(x, "%Y-%m-%d %H:%M:%S"))
# df['Reception Time'] = pd.to_datetime(df['Reception Time']) 
# df['Dispatch Time'] = pd.to_datetime(df['Dispatch Time'])


# Add columns for year, month, day, and weekday
df['Reception Year'] = df['Reception Time'].dt.year
df['Reception Month'] = df['Reception Time'].dt.month
df['Reception Day'] = df['Reception Time'].dt.day
df['Reception Month Name'] = df['Reception Time'].dt.month_name()
df['Reception WeekDay'] = df['Reception Time'].dt.day_name()


# Calculate the time difference in minutes
df['Time Difference (minutes)'] = (df['Dispatch Time'] - df['Reception Time']).dt.total_seconds() / 60

# Print the dataframe
df

Output:

 

※ 위에서 pd.to_datetime()으로도 변환이 가능합니다. 코드가 더 간결해서 쓰기 쉬운데, strptime과 차이가 있습니다.
to_datetime을 쓰는 경우 pandas에서 제공하는 Timestamp, Timedelta 클래스를 이용하는 것이며, strptime은 datetime 클래스에서 제공하는 것으로 차이가 있습니다.

728x90

댓글