반응형
Python datetime 모듈
Available Types
datetime 사용
현재 날짜 가져오기
- datetime. 을 생략하고 싶으면 from datetime import datetime 으로
import datetime
datetime.datetime.today()
datetime.datetime.now()
print(datetime.datetime.now()) # 2020-01-07 15:40:15.087337
now = datetime.datetime.now()
print(now) # 2020-01-07 15:40:15.087337
년, 월, 일, 시, 분, 초
import datetime
now = datetime.datetime.now()
print(now.year) # 2020
print(now.month) # 1
print(now.day) # 7
print(now.hour) # 15
print(now.minute) # 40
print(now.second) # 15
print(now.microsecond) # 087337
날짜, 시간 연산 : datetime.timedelta(시간 단위=숫자)
- # 시간 단위는 weeks, days, hours, minutes, seconds, milliseconds, microseconds 사용 가능
import datetime
now = datetime.datetime.now()
print(now + datetime.timedelta(weeks=1)) # 2020-01-14 15:40:15.087337
print(now + datetime.timedelta(days=1)) # 2020-01-08 15:40:15.087337
print(now + datetime.timedelta(hours=5, minutes=10)) # 2020-01-07 20:50:15.087337
반응형
지난달 구하기
import datetime
from dateutil.relativedelta import relativedelta
now = datetime.datetime.now()
last_month = now - relativedelta(months=1)
last_month = last_month.strftime('%Y/%m')
시간을 문자열로 (원하는 포맷으로) : strftime()
import datetime
now = datetime.datetime.now()
print(now.strftime('%Y-%m-%d')) # 2020-01-07
print(now.strftime('%H:%M:%S')) # 15:40:15
print(now.strftime('%Y-%m-%d %H:%M:%S')) # 2020-01-07 15:40:15
시간 포맷의 문자열을 시간 형식으로 : strptime()
import datetime
now = datetime.datetime.now()
print(datetime.datetime.strptime('2020-01-07 15:40:15', '%Y-%m-%d %H:%M:%S'))
# 2020-01-07 15:40:15
print(type(datetime.datetime.strptime('2020-01-07 15:40:15', '%Y-%m-%d %H:%M:%S')))
# <class 'datetime.datetime'>
요일 구하기
import datetime
def what_day_is_today(self):
now = datetime.datetime.now()
t = ['월', '화', '수', '목', '금', '토', '일']
r = datetime.datetime.today().weekday()
day = str(now.year) + '년 ' + str(now.month) + '월 ' + str(now.day) + '일 ' + t[r] + '요일'
return day
반응형
댓글