본문 바로가기

Programming Language/[Python]

[Python] datetime format

728x90
반응형

python datetime 공식문서

YYYYMMDD 형식으로 파라미터를 입력 받아서 sql 쿼리에 사용할 때 유용하게 사용하는 tip 이다.

import datetime


target_date_str = '20230418'

target_date_formatted = f"{target_date_str[:4]}-{target_date_str[4:6]}-{target_date_str[6:8]}"
print(target_date_formatted)

target_dt_formatted = f"{target_date_formatted} 00:00:00"
print(target_dt_formatted)

target_date_formatted_utc = (
    datetime.datetime.strptime(target_dt_formatted, "%Y-%m-%d %H:%M:%S") - datetime.timedelta(hours=9)
).strftime("%Y-%m-%d %H:%M:%S")
print(target_date_formatted_utc)

target_date_14days_ago_utc = (
    datetime.datetime.strptime(target_date_formatted_utc, "%Y-%m-%d %H:%M:%S") - datetime.timedelta(days=14)
).strftime("%Y-%m-%d %H:%M:%S")
print(target_date_14days_ago_utc)

결과:

2023-04-18
2023-04-18 00:00:00
2023-04-17 15:00:00
2023-04-03 15:00:00
반응형

'Programming Language > [Python]' 카테고리의 다른 글

[Python] pymysql connection option  (0) 2023.06.21
[Python] Jinja template  (0) 2023.04.30
[Python] sqlalchemy - text  (0) 2023.04.18
[Python] Redis connection  (0) 2023.04.15
[Python] PID 의미  (0) 2023.04.15