[Python] string與datetime轉換

string轉換成datetime

語法:datetime.strptime([date_string], [format])

日期格式:官方網站

如:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
from datetime import datetime
print datetime.strptime('2019-01-01','%Y-%m-%d')
from datetime import datetime print datetime.strptime('2019-01-01','%Y-%m-%d')
from datetime import datetime
print datetime.strptime('2019-01-01','%Y-%m-%d')

 

datetime轉換成string

語法:datetime.strftime([datetime], [format])

如:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
from datetime import datetime
now = datetime.now()
s = datetime.strftime(now,'%Y-%m-%d %H:%M:%S')
print type(now)
print now
print s
from datetime import datetime now = datetime.now() s = datetime.strftime(now,'%Y-%m-%d %H:%M:%S') print type(now) print now print s
from datetime import datetime
now = datetime.now()
s = datetime.strftime(now,'%Y-%m-%d %H:%M:%S')
print type(now)
print now
print s