Python/날짜 관련 datetime



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

time = 1541217027247
dt = datetime.utcfromtimestamp(time / 1000.)
date = f"{dt.now():%Y-%m-%d %H:%M:%S}"

2018-11-03 12:51:30

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

이 글에는 0 개의 댓글이 있습니다.