반응형

  현재 년, 월, 일, 시, 분, 초 문자열로 표현하기 (yyyymmddhh24miss 형태) 

## 시간 표시  ##################################### 
import time
import datetime
now = datetime.datetime.now()
nowStr = "{:%Y%m%d%H%M%S}".format(now)
timeserise = time.time()
timeserise = str(int(timeserise))
#print(timeserise)
print(now)
print(" 년월일시분초 :" + nowStr)

#################################################
반응형
반응형

해당 년도 주차별 달력 날짜 정보, ISO 8601

 

https://ko.wikipedia.org/wiki/ISO_8601

 

ISO 8601 - 위키백과, 우리 모두의 백과사전

ISO 8601 Data elements and interchange formats - Information interchange - Representation of dates and times은 날짜와 시간과 관련된 데이터 교환을 다루는 국제 표준이다. 이 표준은 국제 표준화 기구(ISO)에 의해 공포되

ko.wikipedia.org

 

weeknum  정보 

 

ISO 8601 Data elements and interchange formats - Information interchange - Representation of dates and times은 날짜와 시간과 관련된 데이터 교환을 다루는 국제 표준이다. 이 표준은 국제 표준화 기구(ISO)에 의해 공포되었으며 1988년에 처음으로 공개되었다. 이 표준의 목적은 날짜와 시간을 표현함에 있어 명백하고 잘 정의된 방법을 제공함으로써, 날짜와 시간의 숫자 표현에 대한 오해를 줄이고자함에 있는데, 숫자로 된 날짜와 시간 작성에 있어 다른 관례를 가진 나라들간의 데이터가 오갈때 특히 그렇다.

일반적으로, ISO 8601은 그레고리력 (proleptic Gregorian도 가능)에서의 날짜와 (부가적으로 시간대 정보를 포함하는) 24시간제에 기반하는 시간, 시간 간격(time interval) 그리고 그들의 조합에 대한 표현과 형식에 적용된다. 이 표준은 표현할 날짜/시간 요소에 어떠한 특정 의미도 할당하지 않는다; 그 의미는 사용 맥락에 따라 달라질 것이다. 추가로, 표현될 날짜와 시간은 표준 내에서의 지정된 의미의 숫자(예를 들자면, 중국 달력의 년도 이름)가 아니고서는 단어를 포함할 수 없으며 단어들은 문자(예: 이미지, 소리)를 사용하지 않는다.

교환을 위한 표현에서, 날짜와 시간은 재배치되어서, 가장 큰 시간 용어(년도)가 왼쪽에 놓이며 각각의 더 작은 용어들은 이전 용어의 우측에 놓이게 된다. 표현은 아라비아 숫자와 표준 내에서 특정 의미를 제공하는 ("-", ":", "T", "W" 그리고 "Z"와 같은) 어떤 문자들로 작성되어야 한다. 그것이 의미하는 바는, "January" 혹은 "Thursday"처럼 날짜의 일부를 작성하는 어떤 평범한 방법이 교환 표현에서는 허용되지 않는다는 것이다.

Week date 표현은 위 박스에서 볼 수 있는 형식 중 하나다. YYYY는 전통적인 그레고리력의 연도와는 살짝 다른 ISO 주수 연도를 가리킨다. Www는 문자 W를 접두사로 하는 주수로, W01부터 W53까지며 월요일이 시작, 일요일이 끝이다.

* 주의 서로 대등하고 공존 가능한 명세가 존재:

- 01 주 내 연도의 첫번째 목요일이 존재 (공식 ISO 정의),
- 01 주 내 1월 4일이 존재,
- 시작 연도 내 01 주의 일 대부분(4일 이상)을 가진 첫번째 주, 그리고
- 12월 29일부터 1월 4일까지의 기간 내에 있는 월요일로 시작하는 주.


그런 결과로, 1월 1일이 월요일, 화요일, 수요일 혹은 목요일에 있다면, 1월 1일은 01 주 내에 포함된다. 1월 1일이 금요일, 토요일 혹은 일요일이라면, 전년도의 52 주 혹은 53 주에 포함된다 (00주는 없다). 12월 28일은 항상 해당 연도의 마지막 주에 포함된다.

주수(week number)는 목요일을 카운트하여 기술 가능하다: 즉, 12 주는 연도의 12번째 목요일이다.

ISO 주수 매기기 연도는 01 주의 첫번째 날(월요일)에서 시작하며 새로운 ISO 연도 전의 일요일에 끝이 난다(그러므로 겹치거나 격차가 나지 않는다). 연도는 꽉찬 52 혹은 53 주로 구성된다. ISO 주수 매기기 연도의 번호는 (ISO 주수 매기기 이전 연도의 끝인) 전통적인 그레고리력 연도 시작점의 금, 토, 일 혹은 토, 일 혹은 그냥 일요일과 (ISO 주수 매기기 다음 연도의 01 주인) 전통적인 그레고리력 연도의 끝점의 월, 화, 수 혹은 월, 화 혹은 그냥 월요일의 전통 그레고리력 연도의 번호로부터 벗어난다. 목요일에 대해, ISO 주수 매기기 연도 번호는 항상 전통적인 그레고리력 연도 번호와 같다.

예: 2008년 12월 29일 월요일은 "2009-W01-1"로 쓰여진다
    2010년 1월 3일 일요일은 "2009-W53-7"로 쓰여진다

 

반응형
반응형

getDay() 메서드는 지정된 날짜의 요일(0~6)을 반환합니다.

var d = new Date();
var n = d.getDay();

getDay() 메서드는 지정된 날짜의 요일(0~6)을 반환합니다.

참고: 일요일은 0, 월요일은 1 등입니다.

var d = new Date();
var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";

var n = weekday[d.getDay()];

 

https://www.w3schools.com/js/js_date_methods.asp

 

JavaScript Get Date Methods

Method Description
getFullYear() Get the year as a four digit number (yyyy)
getMonth() Get the month as a number (0-11)
getDate() Get the day as a number (1-31)
getHours() Get the hour (0-23)
getMinutes() Get the minute (0-59)
getSeconds() Get the second (0-59)
getMilliseconds() Get the millisecond (0-999)
getTime() Get the time (milliseconds since January 1, 1970)
getDay() Get the weekday as a number (0-6)
Date.now() Get the time. ECMAScript 5.

 

 

반응형
반응형

moment 사용하기

# 폴더 생성 및 열기
mkdir moment_practice
cd moment_practice

# package.json 초기화
npm init -y

# moment.js 설치
npm install moment

현재 날짜: moment()

//현재 날짜: moment()
// moment_practice.js

const moment = require("moment");

// 현재 날짜
console.log("========== today ==========");
console.log(moment());

특정 날짜 지정: moment('date')

// 특정 날짜 지정: moment('date')
// 특정 날짜 지정
console.log("========== specific date ==========");
console.log(moment("2021-01-27", "YYYY-MM-DD")); // Moment<2021-01-27T00:00:00+09:00>

형식 지정: format()

// 형식 지정: format()
// 현재 날짜 형식 지정
console.log("========== format ==========");
let date = moment("2021-01-27");
// 년-월-일
console.log(date.format("YYYY-MM-DD")); // 2021-01-27
// 시:분:초
console.log(date.format("HH:mm:ss")); // 00:00:00
// 요일
console.log(date.format("dddd")); // Wednesday
// 년-월-일 요일
console.log(date.format("YYYY-MM-DD dddd")); // 2021-01-27
// 년-월-일 시:분:초
console.log(date.format("YYYY-MM-DD HH:mm:ss")); // 2021-01-27 00:00:00
// 년-월-일 요일 시:분:초
console.log(date.format("YYYY-MM-DD dddd HH:mm:ss")); // 2021-01-27 Wednesday 00:00:00
// 날짜 더하거나 빼기: add(), subtract()
// 날짜 더하거나 빼기
console.log("========== add or subtract day, month, year ==========");
console.log(moment("2021-01-27").add(1, "days")); // 2021-01-28
console.log(moment("2021-01-27").add(2, "months")); // 2021-03-27
console.log(moment("2021-01-27").add(2, "years")); // 2023-01-27
console.log(moment("2021-01-27").subtract(1, "days")); // 2021-01-26
console.log(moment("2021-01-27").subtract(2, "months")); // 2020-11-27
console.log(moment("2021-01-27").subtract(2, "years")); // 2019-01-27

날짜 더하거나 뺄 때 생길 수 있는 문제점
한 moment 변수를 기준으로 날짜를 연속적으로 더하거나 빼게 되면 해당 변수도 add or subtract 함수를 실행하는 도중 값이 변하게 된다.

// 날짜 더하거나 뺄 때 생길 수 있는 문제점
// 한 moment 변수를 기준으로 날짜를 연속적으로 더하거나 빼게 되면 해당 변수도 add or subtract 함수를 실행하는 도중 값이 변하게 된다.

// 날짜 더하고 뺄 때 문제점
console.log("========== problems when adding or subtracting dates ==========");
let now = moment("2021-01-27");
console.log(now.add(3, "days")); // 2021-01-30
console.log(now.subtract(5, "days")); // 2021-01-25
console.log(now); // 2021-01-25

// 해결 방법: clone()
//add or subtract를 하기 전에 clone() 함수를 사용하면 된다.

// 해결 방법
console.log("========== solutions to the above problems ==========");
let fixedNow = moment("2021-01-27");
console.log(fixedNow.clone().add(3, "days")); // 2021-01-30
console.log(fixedNow.clone().subtract(5, "days")); // 2021-01-22
console.log(fixedNow); // 2021-01-27

https://millo-l.github.io/Nodejs-moment-%EC%82%AC%EC%9A%A9%ED%95%98%EA%B8%B0/

 

[Node.js] moment 사용하기

nodejs에서 moment.js를 사용해보자.

millo-L.github.io

 

반응형
반응형

PostgreSQL 날짜&시간 사용하기

www.postgresql.org/docs/8.4/functions-datetime.html

 

Date/Time Functions and Operators

Table 9-27 shows the available functions for date/time value processing, with details appearing in the following subsections. Table 9-26 illustrates the behaviors of the basic arithmetic operators (+, *, etc.). For formatting functions, refer to Section 9.

www.postgresql.org

www.postgresql.org/docs/8.4/functions-formatting.html

 

Data Type Formatting Functions

The PostgreSQL formatting functions provide a powerful set of tools for converting various data types (date/time, integer, floating point, numeric) to formatted strings and for converting from formatted strings to specific data types. Table 9-20 lists them

www.postgresql.org

해당 날짜의 데이터 

 

select count(watt_max) from tbl_test_watt3_sm2ch_min
where to_char(regdate, 'YYYY-MM-DD') = '2016-10-17'

 

소요시간 : 124초  (150만건)  (하루: 20*60*60*24 = 1,728,000)   이렇게 하면 망함!

 

해당 날짜의 데이터 

 

select count(watt) from tbl_test_watt_lsh where 

regdate >= date '2016-10-17'

and regdate < date '2016-10-17' + integer '1'   // 여기선 하루 

 

소요시간 : 634ms  (150만건)  (하루: 20*60*60*24 = 1,728,000)

 

 

해당 날짜의 데이터 

 

select count(watt) from tbl_test_watt_lsh where 

regdate >=  current_date 

and regdate < current_date + 1

 

소요시간 : 634ms  (150만건)  (하루: 20*60*60*24 = 1,728,000)

 

 

해당 시간의 데이터 

 

select count(watt) from tbl_test_watt_lsh where regdate

between  to_timestamp('2016-10-17 07:40:00' , 'YYYY-MM-DD HH24:MI:SS')  and   to_timestamp('2016-10-17 07:43:00', 'YYYY-MM-DD HH24:MI:SS')

 

소요시간 : 14ms  (3600건)  (하루: 20*60*60*24 = 1,728,000)

 

 

select count(watt) from tbl_test_watt_lsh where regdate

between  to_timestamp('2016-10-17 07:40:00' , 'YYYY-MM-DD HH24:MI:SS')  and   to_timestamp('2016-10-17 07:43:00', 'YYYY-MM-DD HH24:MI:SS') + interval '1'    // 여기선 1초 

 

소요시간 : 14ms  (3620건)

 

 

select count(watt) from tbl_test_watt_lsh where regdate

between  to_timestamp('2016-10-17 07:40:00' , 'YYYY-MM-DD HH24:MI:SS')  and   to_timestamp('2016-10-17 07:43:00', 'YYYY-MM-DD HH24:MI:SS') + interval '1' HOUR   // 여기선 1 시간  

 

소요시간 : 23ms  (63340건)

 

select count(watt) from tbl_test_watt_lsh where regdate

between  to_timestamp('2016-10-17 00:00:00' , 'YYYY-MM-DD HH24:MI:SS')  and   to_timestamp('2016-10-17 00:00:00', 'YYYY-MM-DD HH24:MI:SS') + '1-1 00:00:00' // 여기선 하루 , 인터벌 값을 이렇게 나타낼 수 있다 

 

'10-10' 는 10년 10개월 

 

소요시간 : 433ms  (1496720건)

 

 

select * from tbl_test_watt_lsh where to_char(regdate , 'YYYY-MM-DD HH24;MI:SS') > '2016-10-17 07:40:00' AND  to_char(regdate , 'YYYY-MM-DD HH24;MI:SS') < '2016-10-17 07:43:00'

 

역시 to_char 사용하면 망함!

 

-- 오늘 (date)
select current_date;
 
-- 현재시각 (timestamp)
select now();
select current_timestamp;
 
-- 어제/오늘/내일
select
  current_date - 1 "어제",
  current_date     "오늘",
  current_date + 1 "내일"
;
 
-- day of week
select extract(dow from current_date);    -- 일요일(0) ~ 토요일(6)
select extract(isodow from current_date); -- 월요일(1) ~ 일요일(7)
 
-- day of year
select extract(doy from current_date);
 
-- week of year
select extract(week from current_date);
 
-- 두 날짜 사이의 날수
select '2010-07-05'::date - '2010-06-25'::date;
 

 

반응형
반응형

sublime 단축키 plugin  만들기

 

주석에 날짜를 넣어서 삽입하는 단축키 만들기

 

Tools > Developer > New Plugin... 선택 후 아래와 같이 입력.

import sublime
import sublime_plugin
import time

class InsertDatetimeCommand(sublime_plugin.TextCommand):
	def run(self, edit):
		sel = self.view.sel();
		for s in sel:
			self.view.replace(edit, s, time.strftime("<!-- %Y-%m-%d -->"))

 

그리고, 단축키 등록. 

Preferences > Key Bindings 선택 

[
	{ "keys": ["ctrl+shift+i"], "command": "insert_datetime" }
]

 

반응형
반응형

String으로 된 날짜에 일자를 더해서 세팅

package com.blue.controller;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class CalendarEx2 { 

       public static void main(String[] arg) { 

             // 2019.12.31 + 2일
            DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
             Date date = null;
             try {
                    date = dateFormat.parse("20191231");
             } catch (ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
             }

             Calendar cal = Calendar.getInstance();
             cal.setTime(date);
             cal.add(Calendar.DATE, 2);
             System.out.println(date);
             System.out.println(cal.getTime());
            

             String strDate = dateFormat.format(cal.getTime());
             System.out.println(strDate);
 

       }


}
반응형
반응형

jsp 현재 날짜, 일주일전 날짜, 한달 전 날짜 구하기.

currentCalendar.add 부분에 -값이 아닌 +값을 대입하면 현재 이후의 날짜를 구할 수 있지요.

 

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="java.text.DecimalFormat" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="java.util.Calendar" %>

<%
    DecimalFormat df = new DecimalFormat("00");
    Calendar currentCalendar = Calendar.getInstance();

  //현재 날짜 구하기
    String strYear   = Integer.toString(currentCalendar.get(Calendar.YEAR));
    String strMonth  = df.format(currentCalendar.get(Calendar.MONTH) + 1);
    String strDay   = df.format(currentCalendar.get(Calendar.DATE));
    String strDate = strYear + strMonth + strDay;

  //일주일 전 날짜 구하기
    currentCalendar.add(currentCalendar.DATE, -7);
    String strYear7   = Integer.toString(currentCalendar.get(Calendar.YEAR));
    String strMonth7  = df.format(currentCalendar.get(Calendar.MONTH) + 1);
    String strDay7   = df.format(currentCalendar.get(Calendar.DATE));
    String strDate7 = strYear7 + strMonth7 + strDay7;

  //한달 전 날짜 구하기
    currentCalendar.add(currentCalendar.DATE, -24);
    String strYear31   = Integer.toString(currentCalendar.get(Calendar.YEAR));
    String strMonth31  = df.format(currentCalendar.get(Calendar.MONTH) + 1);
    String strDay31   = df.format(currentCalendar.get(Calendar.DATE));
    String strDate31 = strYear31 + strMonth31 + strDay31;
%>

<!-- 현재날짜 -->
<c:set var="nowdate" value='<%=strDate%>' />
<!-- 일주일전 -->
<c:set var="nowdate7" value='<%=strDate7%>' />
<!-- 한달전 -->
<c:set var="nowdate31" value='<%=strDate31%>' /> 
반응형

+ Recent posts