[MySQL] convert Unix time stamp to Epoch

2015. 11. 28. 13:51·프로젝트 관련 조사/DB
반응형
http://www.epochconverter.com/programming/mysql-from-unixtime.php

 

 

 

그림1

그림1은 unix time을 나타낸다

 

그림2는 Epoch 시간을 나타내며

unix_timestamp() 함수를 써주면 변환이 된다.

 

 

Quick summary

Get current epoch time SELECT UNIX_TIMESTAMP(NOW()) (now() is optional)
Today midnight SELECT UNIX_TIMESTAMP(CURDATE())
Yesterday midnight SELECT UNIX_TIMESTAMP(DATE_ADD(CURDATE(),INTERVAL -1 DAY))
Convert from date to epoch SELECT UNIX_TIMESTAMP(timestring)
Time format: YYYY-MM-DD HH:MM:SS or YYMMDD or YYYYMMDD
Convert from epoch to date SELECT FROM_UNIXTIME(epoch timestamp, optional output format)
The default output is YYYY-MM-DD HH:MM:SS
FROM_UNIXTIME doesn't work with negative timestamps

 

The Mini-Course

Let's first create a simple logging-table and some sample records.
All queries on this page will work with the following table.

copytextpop-up
  • -- Table "mytable" DDL
  •  
  • CREATE TABLE `mytable` (
  • `userId` int(11) NOT NULL,
  • `url` varchar(100) NOT NULL,
  • `epoch` int(11) NOT NULL
  • );
  •  
  • INSERT INTO mytable VALUES(1,'homepage',1225540800);
  • # User 1 visited the url homepage on Nov 1, 2008
  • INSERT INTO mytable VALUES(2,'contact',1225886400);
  • # User 2 visited the url contact on Nov 5, 2008
  • INSERT INTO mytable VALUES(3,'contact',1225972800);
  • # User 3 visited the url contact on Nov 6, 2008
  • INSERT INTO mytable VALUES(4,'homepage',1228132800);
  • # User 4 visited the url homepage on Dec 1, 2008
-- Table "mytable" DDL

CREATE TABLE `mytable` (
  `userId` int(11) NOT NULL,
  `url` varchar(100) NOT NULL,
  `epoch` int(11) NOT NULL
);

INSERT INTO mytable VALUES(1,'homepage',1225540800); 
# User 1 visited the url homepage on Nov 1, 2008
INSERT INTO mytable VALUES(2,'contact',1225886400); 
# User 2 visited the url contact on Nov 5, 2008
INSERT INTO mytable VALUES(3,'contact',1225972800); 
# User 3 visited the url contact on Nov 6, 2008
INSERT INTO mytable VALUES(4,'homepage',1228132800); 
# User 4 visited the url homepage on Dec 1, 2008

Converting to readable dates

copytextpop-up
  • SELECT userId, url, FROM_UNIXTIME(epoch) FROM mytable
SELECT userId, url, FROM_UNIXTIME(epoch) FROM mytable

This query outputs:

1   homepage   2008-11-01 13:00:00
2   contact   2008-11-05 13:00:00
3   contact   2008-11-06 13:00:00
4   homepage   2008-12-01 13:00:00

You can format your date by using specifiers (look below for a list of specifiers).

copytextpop-up
  • SELECT userId, url, FROM_UNIXTIME(epoch,"%Y-%m-%d") FROM mytable
SELECT userId, url, FROM_UNIXTIME(epoch,"%Y-%m-%d") FROM mytable

Output:

1   homepage   2008-11-01
2   contact   2008-11-05
3   contact   2008-11-06
4   homepage   2008-12-01

Grouping Epochs

Let's say you want to get statistics by month. This query groups months, and counts the number of visitor (records) in each month. We order by epoch to get all results in the right order.

copytextpop-up
  • SELECT DISTINCT FROM_UNIXTIME(epoch,"%M, %Y") AS month, count(*) as numberOfVisits
  • FROM mytable
  • GROUP BY month
  • ORDER BY epoch
SELECT DISTINCT FROM_UNIXTIME(epoch,"%M, %Y") AS month, count(*) as numberOfVisits
FROM mytable
GROUP BY month
ORDER BY epoch

This outputs:

November, 2008   3
December, 2008   1

This query can be easily changed to get statistics per year, per day, per day of the week, per hour of the day etc. For example, to get yearly stats change the query to:

copytextpop-up
  • SELECT DISTINCT FROM_UNIXTIME(epoch,"%Y") AS year, count(*) as numberOfVisits
  • FROM mytable
  • GROUP BY year
  • ORDER BY epoch
SELECT DISTINCT FROM_UNIXTIME(epoch,"%Y") AS year, count(*) as numberOfVisits
FROM mytable
GROUP BY year
ORDER BY epoch

Adding a new record to our database

Use the UNIX_TIMESTAMP() function to convert MySQL dates/times (such as now() = current time) to epochs.

copytextpop-up
  • INSERT INTO mytable VALUES(1,'pagename',UNIX_TIMESTAMP(now()))
INSERT INTO mytable VALUES(1,'pagename',UNIX_TIMESTAMP(now()))

or use YYYY-MM-DD HH:MM:SS :

copytextpop-up
  • INSERT INTO mytable VALUES(1,'pagename',UNIX_TIMESTAMP('2008-12-01 12:00:00'))
INSERT INTO mytable VALUES(1,'pagename',UNIX_TIMESTAMP('2008-12-01 12:00:00'))

Negative Epochs

There's one big problem with MySQL: MySQL cannot convert negative epoch timestamps (dates before 1-1-1970). This creates problems with for example birthdates. But there are workarounds.

When converting from epoch to human readable date use the DATE_ADD function:

copytextpop-up
  • # converting to MySQL date:
  • SELECT DATE_ADD(FROM_UNIXTIME(0), interval -315619200 second);
  • # converting your epoch to a date string:
  • SELECT DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), interval -315619200 second),'%Y-%m-%d');
# converting to MySQL date:
SELECT DATE_ADD(FROM_UNIXTIME(0), interval -315619200 second);
# converting your epoch to a date string:
SELECT DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), interval -315619200 second),'%Y-%m-%d');

Where -315619200 is your negative epoch. This query returns: 1960-01-01 01:00:00

When converting normal dates to epoch use TIMESTAMPDIFF:

copytextpop-up
  • SELECT TIMESTAMPDIFF(second,FROM_UNIXTIME(0),'1960-01-01 00:00:00' );
SELECT TIMESTAMPDIFF(second,FROM_UNIXTIME(0),'1960-01-01 00:00:00' );

Replace the 1960 date with your date in your local timezone (MySQL time_zone).

MySQL date format specifiers

Specifier Description
%a Abbreviated weekday name (Sun..Sat)
%b Abbreviated month name (Jan..Dec)
%c Month, numeric (0..12)
%D Day of the month with English suffix (0th, 1st, 2nd, 3rd, ...)
%d Day of the month, numeric (00..31)
%e Day of the month, numeric (0..31)
%f Microseconds (000000..999999)
%H Hour (00..23)
%h Hour (01..12)
%I Hour (01..12)
%i Minutes, numeric (00..59)
%j Day of year (001..366)
%k Hour (0..23)
%l Hour (1..12)
%M Month name (January..December)
%m Month, numeric (00..12)
%p AM or PM
%r Time, 12-hour (hh:mm:ss followed by AM or PM)
%S Seconds (00..59)
%s Seconds (00..59)
%T Time, 24-hour (hh:mm:ss)
%U Week (00..53), where Sunday is the first day of the week
%u Week (00..53), where Monday is the first day of the week
%V Week (01..53), where Sunday is the first day of the week; used with %X
%v Week (01..53), where Monday is the first day of the week; used with %x
%W Weekday name (Sunday..Saturday)
%w Day of the week (0=Sunday..6=Saturday)
%X Year for the week where Sunday is the first day of the week, numeric, four digits; used with %V
%x Year for the week, where Monday is the first day of the week, numeric, four digits; used with %v
%Y Year, numeric, four digits
%y Year, numeric (two digits)
%% A literal '%' character

 

반응형
저작자표시 (새창열림)

'프로젝트 관련 조사 > DB' 카테고리의 다른 글

[MySQL] MySQL 기본 character set 설정하기  (0) 2015.11.30
[MySQL] 최근 1주일 데이터 가져오기  (0) 2015.11.28
[MySQL] csv 파일을 직접 MySQL 테이블로 Import 하는 방법 (대용량 파일 import 팁)  (0) 2015.11.27
[MySQL] ISODate를 MySQL에 집어 넣기  (0) 2015.11.12
[MySQL] 테이블 생성, 컬럼 추가, 삭제, 수정  (0) 2015.11.12
'프로젝트 관련 조사/DB' 카테고리의 다른 글
  • [MySQL] MySQL 기본 character set 설정하기
  • [MySQL] 최근 1주일 데이터 가져오기
  • [MySQL] csv 파일을 직접 MySQL 테이블로 Import 하는 방법 (대용량 파일 import 팁)
  • [MySQL] ISODate를 MySQL에 집어 넣기
호레
호레
창업 / IT / 육아 / 일상 / 여행
    반응형
  • 호레
    Unique Life
    호레
  • 전체
    오늘
    어제
    • 분류 전체보기
      • 법률
        • 기본
        • 개인정보보호법
        • 정보통신망법
        • 전자금융거래법
        • 전자금융감독규정
        • 신용정보법
        • 온라인투자연계금융업법
      • 창업
        • 외식업 관련
        • 임대업 관련
        • 유통업 관련
        • 세무 관련
        • 마케팅 관련
        • 기타 지식
        • 트렌드
        • Youtube
      • IT기술 관련
        • 모바일
        • 윈도우
        • 리눅스
        • MAC OS
        • 네트워크
        • 빅데이터 관련
        • A.I 인공지능
        • 파이썬_루비 등 언어
        • 쿠버네티스
        • 기타 기술
      • 퍼블릭 클라우드 관련
        • Azure
        • GCP
        • AWS
      • 정보보안 관련
        • QRadar
        • Splunk
        • System
        • Web
      • 기타
        • 세상 모든 정보
        • 서적
      • 게임 관련
        • 유니티
      • 부동산
      • 맛집 찾기
        • 강남역
        • 양재역
        • 판교역
        • ★★★★★
        • ★★★★
        • ★★★
        • ★★
        • ★
      • 결혼_육아 생활
        • 리얼후기
        • 일상
        • 육아
        • 사랑
        • Food
      • 영어
        • 스피킹
        • 문법
        • 팝송
        • 영화
      • K-컨텐츠
        • 드라마
        • 영화
        • 예능
      • 독서
      • 프로젝트 관련 조사
        • 시스템 구축
        • 로그 관련
        • 웹
        • APT
        • 모의 해킹
        • DB
        • 허니팟
        • 수리카타
        • 알고리즘
        • FDS
      • 기업별 구내 식당 평가
        • 한국관광공사
        • KT telecop
        • KT M&S
        • KT powertel
        • KT cs 연수원
        • 진에어
      • 대학 생활
        • 위드윈연구소
        • 진로 고민
        • 채용정보
        • 자동차
        • 주식
        • 악성코드
        • 게임 보안
      • 쉐어하우스
  • 블로그 메뉴

    • 홈
    • 게임 관련
    • IT 기술 관련
    • 태그
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    AWS
    수제버거
    맛집
    판교맛집
    복리후생
    무역전쟁
    수제버거맛집
    마케팅
    대통령
    쥬쥬랜드
    런치
    판교역
    보안가이드
    상호관세
    수제버거존맛
    점심
    이재곧죽습니다
    돈까스
    유니티
    판교
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.0
호레
[MySQL] convert Unix time stamp to Epoch
상단으로

티스토리툴바