python

[python] 날짜 데이터

전감자(◔◡◔) 2022. 9. 27. 18:05
'''
  날짜 데이터
     from datetime import datetime
'''
from datetime import datetime

print(dir(datetime))
'''
['__add__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', 
'__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', 
'__le__', '__lt__', '__ne__', '__new__', '__radd__', '__reduce__', '__reduce_ex__', 
'__repr__', '__rsub__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', 
'astimezone', 'combine', 'ctime', 'date', 'day', 'dst', 'fold', 
'fromisocalendar', 'fromisoformat', 'fromordinal', 'fromtimestamp', 
'hour', 'isocalendar', 'isoformat', 'isoweekday', 'max', 'microsecond', 
'min', 'minute', 'month', 'now', 'replace', 'resolution', 'second', 'strftime', 
'strptime', 'time', 'timestamp', 'timetuple', 'timetz', 'today', 'toordinal', 'tzinfo', 
'tzname', 'utcfromtimestamp', 'utcnow', 'utcoffset', 'utctimetuple', 'weekday', 'year']
'''

print("1. 현재날짜:", datetime.now() ) # 2022-09-23 17:34:39.726214
print("1. 현재날짜:", datetime.today() ) # 2022-09-23 17:34:39.726214

print("2. 년도 구하기:", datetime.today().year ) # 2022
print("3. 월 구하기:", datetime.today().month ) # 9
print("4. 일 구하기:", datetime.today().day ) # 23
print("5. 시간 구하기:", datetime.today().hour ) # 17
print("6. 분 구하기:", datetime.today().minute ) # 34
print("7. 시간 구하기:", datetime.today().second ) # 39
print("8. 밀리초 구하기:", datetime.today().microsecond ) # 726214

# 특정 날짜 설정 ( 2002년 05월 06일 )
new_date= datetime(2002, 5, 6, 17, 34, 39)
new_date= datetime(2002, 5, 6, minute=17, second=34)
time_dict={
    "year":2002,
    "month":5,
    "day": 6
}
new_date = datetime(**time_dict) # ==> **time_dict는 (year=2002, month=5 , day=6)로 unpacking 됨.
print(new_date)

# 문자열 ==> 날짜로 , datetime.strptime("날짜형태의문자", format) , parse
# https://dojang.io/mod/page/view.php?id=2463
new_date = datetime.strptime("2002-05-06 17:34:39", "%Y-%m-%d %H:%M:%S" )
new_date = datetime.strptime("20020506173439", "%Y%m%d%H%M%S" ) # 권장
print(new_date, type(new_date)) # <class 'datetime.datetime'>

# 날짜 ==> 문자열  , datetime.strftime(format) ,  format
str_date = new_date.strftime("%Y-%m-%d %H:%M:%S")
print(str_date, type(str_date)) # <class 'str'>