1. Today #

from datetime import datetime

date = f"{datetime.now():%Y-%m-%d}" # today

2018-11-03

2. 문자열로부터 datetime 입력 #

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

3. datetime to timestamp #

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

4. 시간 더하고 빼기 timedelta #

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

5. Epoch & Unix Timestamp Conversion #

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

6. Get an UTC #

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

7. timedelta 크기 비교 #

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
Retrieved from http://hyacinth.byus.net/moniwiki/wiki.php/Python/날짜 관련 datetime
last modified 2022-02-02 14:26:48