잠토의 잠망경

[Python] String to Date 본문

공부/Python

[Python] String to Date

잠수함토끼 2020. 4. 15. 14:34

관련 github

https://github.com/yiwonjae/Project_Stock_Markets_Python/blob/master/Sample01/20200415_01.py


방법 1

def Make_Date_01():
    #https://www.programiz.com/python-programming/datetime/strftime
    from datetime import datetime, timedelta
    
    # 현재 시간 얻어오기
    now    = datetime.now()            # 현재 시간을 얻어 온다.
    before = now - timedelta(days=10)  # 현재 시간 기준 10일 전 시간을 얻는다. 

    print(before)
    print(now)

    strBefore:str = before.strftime("%Y%m%d, %H:%M:%S")
    strNow:str    = now.strftime("%Y%m%d, %H:%M:%S")

    print(strBefore)
    print(strNow)

	
    # String to DateTime
    print(datetime.strptime("20190201","%Y%m%d"))

 

방법 2

def Make_Date_02():

    import pandas as pd

    startDate = "2020/01/31" #"10/10/2011"
    endDate   = pd.to_datetime(startDate) + pd.DateOffset(days=5)
    otherDate = pd.to_datetime(startDate) - pd.DateOffset(days=5)

    print(startDate)      # 2020/01/31
    print(endDate)        # 2020-02-05 00:00:00
    print(otherDate)      # 2020-01-26 00:00:00

    print(type(endDate))  # <class 'pandas._libs.tslibs.timestamps.Timestamp'>

    print(pd.to_datetime("2011/10/11")) # 2011-10-11 00:00:00

 

 

Comments