[[TableOfContents]] === Today === {{{#!python from datetime import datetime date = f"{datetime.now():%Y-%m-%d}" # today }}} ---- {{{ 2018-11-03 }}} === 문자열로부터 datetime 입력 === {{{#!python from datetime import datetime, timedelta t1 = "2017-11-11T08:59:00" t2 = "2017-11-10T08:59:00" dt1 = datetime.strptime(t1, '%Y-%m-%dT%H:%M:%S') dt2 = datetime.strptime(t2, '%Y-%m-%dT%H:%M:%S') print (dt1) print (dt2) }}} ---- {{{ 2017-11-11T08:59:00 2017-11-10T08:59:00 }}} === datetime to timestamp === {{{#!python import time from datetime import datetime, timedelta dt1 = datetime.strptime("2017-11-11T08:59:00", '%Y-%m-%dT%H:%M:%S') dt2 = datetime.strptime("2017-11-10T08:59:00", '%Y-%m-%dT%H:%M:%S') timestamp1 = time.mktime(dt1.timetuple()) timestamp2 = time.mktime(dt2.timetuple()) print (timestamp1) print (timestamp2) }}} ---- {{{ 1510358340.0 1510271940.0 }}} === 시간 더하고 빼기 timedelta === {{{#!python from datetime import datetime, timedelta yesterday = datetime.now() - timedelta(days=1) print (datetime.now()) print (yesterday) }}} ---- {{{ 2018-11-03 12:57:10.385943 2018-11-02 12:57:10.385943 }}} === Epoch & Unix Timestamp Conversion === {{{#!python from datetime import datetime timestamp1 = 1541217027247 # milliseconds Timestamp dt = datetime.utcfromtimestamp(timestamp1 / 1000.) # GMT date = f"{dt:%Y-%m-%d %H:%M:%S}" timestamp2 = 1528797322 # Unix epoch time dt = datetime.fromtimestamp(timestamp2) # System Timezone date = f"{dt:%Y-%m-%d %H:%M:%S}" }}} ---- {{{ 2018-11-03 12:51:30 2018-06-12 18:55:22 }}} === Get an UTC === {{{#!python import pytz from datetime import datetime, timedelta print (datetime.now(pytz.utc).strftime("%Y-%m-%d %H:%M:%S")) }}} ---- {{{ 2018-11-03 03:51:30 }}} === timedelta 크기 비교 === {{{#!python s1 = "2018-06-1911:30" s2 = "2018-06-1911:24" tm1 = datetime.strptime(s1, '%Y-%m-%d%H:%M') tm2 = datetime.strptime(s2, '%Y-%m-%d%H:%M') delta = tm1 - tm2 print (delta < timedelta(minutes=5)) print (delta < timedelta(minutes=7)) }}} ---- {{{ False True }}}