달나라 노트

Python Pandas : dt.strftime() (dataframe에서 date type을 string으로 변환, convert datetime to string in dataframe) 본문

Python/Python Pandas

Python Pandas : dt.strftime() (dataframe에서 date type을 string으로 변환, convert datetime to string in dataframe)

CosmosProject 2025. 9. 28. 03:21
728x90
반응형

 

 

 

 

데이터를 다루다보면 날짜 데이터를 다양한 data type으로 바꿔야할 때가 많습니다.

 

dataframe에 담긴 date type 데이터를 어떻게 텍스트나 숫자의 형태로 바꿀 때 유용하게 사용할 수 있는 함수가 dt.strftime입니다.

 

 

Syntax

series.dt.strftime(format)

 

dt.strftime은 Series에 적용할 수 있습니다.

그리고 parameter로 format을 받는데, date type의 데이터를 어떤 format의 string으로 바꿀지를 의미합니다.

 

format은 다양한 기호로 적혀지는데 datetime format 기호 관련해서는 아래 글을 참조하면 좋습니다.

https://cosmosproject.tistory.com/106

 

Python datetime : strftime(시간 날짜 데이터를 텍스트로) & strptime(텍스트를 시간 날짜 데이터로)

2020-03-08이라는 날짜를 표현하는 방식은 다양합니다. 2020-03-08이라고 표현할 수도 있으며 2020/03/08, 03/08/2020, 03-08-2020, 08-03-2020 등등 여러 구분기호(-, / etc)와 년, 월, 일의 순서를 변경할 수도 있습

cosmosproject.tistory.com

 

 

 

 

아래는 str.strftime method를 적용한 예시입니다.

import pandas as pd
import datetime

val_now = datetime.datetime.now()

# 1 현재 날짜와 시간을 담은 dataframe 생성
df = pd.DataFrame({
    'date1': [val_now, val_now, val_now],
})
print(df)  # 2 테스트용 dataframe 출력
print(df[['date1']].dtypes)  # 3 date1 column이 datetime64 type인 것을 확인

# 4 date1 column을 yyyymmdd 형태의 string으로 바꾸기 위해 strftime 적용
df.loc[:, 'date1_converted1'] = df.loc[:, 'date1'].dt.strftime('%Y%m%d')

# 5 date1 column을 yyyy-mm-dd 형태의 string으로 바꾸기 위해 strftime 적용
df.loc[:, 'date1_converted2'] = df.loc[:, 'date1'].dt.strftime('%Y-%m-%d')

# 6 date1 column을 yyyy-mm-dd 형태의 string으로 바꾸기 위해 strftime 적용
df.loc[:, 'date1_converted3'] = df.loc[:, 'date1'].dt.strftime('%Y/%m/%d')

print(df)  # 7 결과 출력

# 8 변환된 column들의 값이 의도한 형태의 날짜 형식의 string으로 표시되는 것 확인
print(df[['date1', 'date1_converted1', 'date1_converted2', 'date1_converted3']].dtypes)


-- Result
                       date1
0 2025-09-28 03:20:21.943613
1 2025-09-28 03:20:21.943613
2 2025-09-28 03:20:21.943613

date1    datetime64[ns]
dtype: object

                       date1 date1_converted1 date1_converted2 date1_converted3
0 2025-09-28 03:20:21.943613         20250928       2025-09-28       2025/09/28
1 2025-09-28 03:20:21.943613         20250928       2025-09-28       2025/09/28
2 2025-09-28 03:20:21.943613         20250928       2025-09-28       2025/09/28

date1               datetime64[ns]
date1_converted1            object
date1_converted2            object
date1_converted3            object
dtype: object

 

 

 

 

 

 

 

 

 

 

 

728x90
반응형
Comments