안녕세계

[Python] datetime, timestamp 변환 본문

Python/Tip

[Python] datetime, timestamp 변환

Junhong Kim 2018. 3. 26. 17:48
728x90
반응형

timestamp 만들기

timestamp = 초 * 분 * 시 * 일

timestamp = 60 * 60 * 24 * 30 print(timestamp) # 2592000

str 으로 변환

timestamp ➠ str

import time timestamp = time.time() s = str(timestamp) print(s) # 1522049204.295597

datetime ➠ str

from datetime import datetime s = datetime.now().strftime('%Y-%m-%d %H:%M:%S') print(s) # 2018-03-26 16:27:00

timestamp 로 변환

str ➠ timestamp

from datetime import datetime import time s = '2018-03-26 12:12:12' timestamp = time.mktime(datetime.strptime(s, '%Y-%m-%d %H:%M:%S').timetuple()) print(timestamp) # 1522033932.0

datetime ➠ timestamp

from datetime import datetime import time timestamp = time.mktime(datetime.today().timetuple()) print(timestamp) # 1522049257.0

datetime 으로 변환

str ➠ ︎datetime

from datetime import datetime s = '2018-03-26 12:12:12' dt = datetime.strptime(s, '%Y-%m-%d %H:%M:%S') print(dt, type(dt)) # 2018-03-26 12:12:12 <class 'datetime.datetime'>

timestamp ➠ datetime

from datetime import datetime import time d = datetime.fromtimestamp(time.time()) print(d) # 2018-03-26 16:28:28.581626

사용 예제

두 날짜간의 일수 구하기(1)

from datetime import datetime import time since_timestamp = time.mktime(datetime.strptime('20180301', '%Y%m%d').timetuple()) until_timestamp = time.mktime(datetime.strptime('20180331', '%Y%m%d').timetuple()) days = (datetime.fromtimestamp(until_timestamp) - datetime.fromtimestamp(since_timestamp)).days print(days) # 30

두 날짜간의 일수 구하기(2)

from datetime import datetime since_timestamp = datetime.strptime('20180301', '%Y%m%d') until_timestamp = datetime.strptime('20180331', '%Y%m%d') result = until_timestamp - since_timestamp print(result) # 30 days, 0:00:00 print(result.days) # 30 print(result.seconds) # 0

현재 날짜로부터 1주일 뒤

from datetime import datetime, timedelta now = datetime.now() print(now) # 2018-03-26 16:39:13.496734 next_week = now + timedelta(days=7) print(next_week) # 2018-04-02 16:39:13.496734
  • 1주: timedelta(weeks=1)
  • 1일: timedelta(days=1)
  • 1시간: timedelta(hours=1)
    • 1시간 30분: timedelta(hours=1, minutes=30)
  • 1분: timedelta(minutes=1)
  • 1초: timedelta(seconds=1)
  • 1밀리초: timedelta(milliseconds=1)
  • 1마이크로초: timedelta(microseconds=1)

특정일 요일 구하기

import datetime def get_yoil(y, m, d): days = ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN'] return days[datetime.date(y, m, d).weekday()] print(get_yoil(2018, 3, 30))


반응형
0 Comments
댓글쓰기 폼