CAFE

Python

날짜 및 시간 관련 명령어

작성자ParkYK|작성시간16.07.25|조회수249 목록 댓글 0

연습1

print("날짜 및 시간 관련 작업 ------------")

import time

print(time.time())     #time stamp : 1970년 1월 1일 이후 현재까지 누적된 타임스템프

time.sleep(3)          #3초 간 처리 일시 정지

print(time.time())

 

print()

print(time.localtime())                    #시스템의 현재 날짜 및 시간 반환

print(time.asctime(time.localtime()))  #Mon Jul 25 11:28:50 2016와 같이 이미 지정된 형식으로 결과 반환

 

print("\n사용자가 정의한 형식으로 날짜 및 시간 출력용 함수 : strftime()")

from time import localtime, strftime

print(strftime("%Y-%m-%d %H:%M:%S"), localtime())  #형식 지시자를 사용해 연월일시분초 출력

print(strftime("%Y %y"), localtime())         #Y:연도, y:축약연도 출력

print(strftime("%B %b %m"), localtime())   #B:월이름, b:축약월이름, m:월숫자 출력

print(strftime("%p %H %I"), localtime())     #p:오전오후, H:24시간제, I:24시간제 출력

print(strftime("%A %a %w"), localtime())    #A요일이름, a:축약요일이름, w:요일숫자(일:0 ~ 토:6) 출력

print(strftime("%j"), localtime())                #j:1월1일부터 오늘까지 누적된 날수 출력(1-366)

 

print("\n날짜 및 시간 관련 클래스 ------------")

import datetime

nalja = datetime.date.today()

print(str(nalja.year) + "년 " + str(nalja.month) + "월 " + str(nalja.day))

print(nalja.isoformat())        #date 객체의 출력형태를 YYYY-MM-DD 형식의 문자열로 출력

print(nalja.ctime())             #date 객체의 출력형태를 Mon Jul 25 00:00:00 2016 형식의 문자열로 출력

 

print()

print(datetime.datetime.now())                                     #시스템의 현재 날짜 및 시간 반환

print(datetime.datetime.date(datetime.datetime.now()))      #날짜 반환

print(datetime.datetime.date(datetime.datetime.now()))      #날짜 반환

print(datetime.datetime.time(datetime.datetime.now()))      #시간 반환

print(datetime.datetime.weekday(datetime.datetime.now())) #요일(월:0 ~ 일:6) 반환

 

 

*** 년월일시분 얻기 함수 작성 ***

import datetime

def getNowDate():

    now = datetime.datetime.now()

    year = now.year

    month = now.month

    day = now.day

    hour = now.hour

    minute = now.minute

 

    nowDate = str(year)+"년 "+str(month)+"월 "+str(day)+"일 "+str(hour)+"시 "+str(minute) + "분"

    return nowDate

 

print(getNowDate())

 

 

 

연습2

'''

시간 표현하기

Time Stamp: 1970년 1월 1일 자정을 기준으로 지난 시간을 초 또는 1/1000초 단위의 정수로 가지는 것으로 보통 epoch time이라 한다.

 - UTC(Universal Time Coordinated) : 1972년 부터 시행된 국제 표준시로 세슘 원자의 진동수에 의거한 초의 길이

 - GMT(Greenwich Mean Time 세계협정시) : UTC(세계협정시)는 영국 그리니치 천문대(경도 0)를 기준으로 하는 세계의 표준         시간대로서, 동경 135도를 표준시로 하는 우리나라보다는 9시간이 느리다(한국은 UTC+9).

 - 지방 표준시(LST, Local Standard Time): UTC를 기준으로 경도 15도마다 1시간 차이가 발생하는 시간.

 

struct_time 시퀀스 객체(구조체)

Tm_year, tm_mon, tm_mday, tm_hour, tm_min, tm_sec, tm_wday, tm_yday, tm_isdst

time.time() : 1970년 1월 1일 자정 이후로 누적된 초를 float으로 반환

time.sleep(secs) : 현재 동작 중인 스레드를 주어진 초 만큼 정지

time.gmtime([secs]) : 입력된 초를 반환해서 struct_time 시퀀스 객체로 반환하는데 파라미터를 대입하지 않으면 현재 시간

time.localtime([secs]) : 지방 표준시 기준으로 struct_time 시퀀스 객체 반환

'''

 

import time

print(time.time())         #1970년 1월 1일 부터 누적된 시간

print(time.gmtime())     #UTC 시간

print(time.localtime())    #현재 지역의 시간

time.sleep(3)

 

print()

import datetime

dt = datetime.datetime.now()

print("현재시간:", dt)

print(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond, dt.tzinfo)

print("요일:",dt.weekday())

dt1 = datetime.datetime.strptime("2017-12-31 10:23", "%Y-%m-%d %H:%M")

print(dt1)

s = dt1.strftime('%Y %m %d %H %M %S')

print(s)

'''

datetime.datetime 클래스 포맷 기호

%Y : 네자리 년도, %y : 두자리 년도

%m : 두자리 월, %d : 두자리 일

%H : 24시간, %I : 12시간

%M : 분, zero-padded decimal

%S : 초, zero-padded decimal

'''

 

print('-----------------')

from pandas import Series

import pandas as pd

import numpy as np

 

ran = pd.date_range('1/1/2017', periods=30, freq='T')

ts = Series(np.arange(30), index = ran)

print(ts)

 

print()

#10분 단위 합계 구하기

print(ts.resample('10T').sum())

'''

Resampling : 시계열의 빈도를 변환하는 과정

  상위 빈도의 데이터를 하위 빈도로 집계하는 것을 다운샘플링이라고 하고 반대의 과정을 업샘플링이라고 한다.

  resample(freq, how, fill_method, closed, label, kind)

  freq : 리샘플링 빈도(‘M’, ‘5min’, Second(15)

  how : 집계값으로 기본은 mean으로 first, last, median, max, min 등

  fill_method : 업 샘플링을 할 때 데이터를 채우는 방법으로 기본은 None 이고 ffill 또는 bfill 설정 가능

  limit : 채우는 개수

  closed : 다운 샘플링을 할 때 왼쪽과 오른쪽 어느 쪽을 포함시킬 지 설정

  label : 다운 샘플링을 할 때 왼쪽과 오른쪽 어느 쪽 라벨을 사용할 것인지 설정

'''

 

 

다음검색
현재 게시글 추가 기능 열기

댓글

댓글 리스트
맨위로

카페 검색

카페 검색어 입력폼