[C++][Python]YYYYMMDDHHMMSS

spring·2021년 12월 21일
0

UTC time yyyymmddhhmmss

UTC를 출력하는 방법을 언어별로 정리

C++ (UTC yyyymmddhhmmss)
time_t t = time(nullptr);
struct tm buf;
gmtime_s(&buf, &t);
int year = 1900 + buf.tm_year;
int month = buf.tm_mon + 1;
int day = buf.tm_mday;
int hour = buf.tm_hour;
int minute = buf.tm_min;
int second = buf.tm_sec;
char time_str[128] = { 0 };
sprintf_s(time_str, "%4d/%02d/%02d %02d:%02d:%02d", year, month, day, hour, minute, second);
std::cout << time_str << std::endl;
Python (UTC yyyymmddhhmmss)
import datetime
s = datetime.datetime.utcnow().strftime("%Y/%m/%d %H:%M:%S")
print(s)
python (Asia/Seoul)
from pytz import timezone
from datetime import datetime

KST = timezone('Asia/Seoul')

s = datetime.now().astimezone(KST).strftime("%Y/%m/%d %H:%M:%S.%f")
print(s)

시간 차이 구하기

위 포맷대로 문자열을 출력하였다면 아래와 같이 datetime클래스로 변경해서 차이를 구할 수 있다.
아래의 예시는 초(seconds) 차이를 구하는 예시

아래처럼 하면 안됩니다.

diff = datetime.strptime(timestr1, '%Y/%m/%d %H:%M:%S') - datetime.strptime(timestr2, '%Y/%m/%d %H:%M:%S')
print(diff.seconds)

아래처럼 해야 합니다.

if timestr1 > timestr2:
    diff = datetime.strptime(timestr1, '%Y-%m-%d-%H-%M-%S') -  datetime.strptime(timestr2, '%Y-%m-%d-%H-%M-%S')
else:
    diff = datetime.strptime(timestr2, '%Y-%m-%d-%H-%M-%S') - datetime.strptime(timestr1, '%Y-%m-%d-%H-%M-%S')
print(diff.seconds)
diff = abs(datetime.strptime(timestr1, '%Y-%m-%d-%H-%M-%S') -  datetime.strptime(timestr2, '%Y-%m-%d-%H-%M-%S'))
print(diff.seconds)

References

profile
Researcher & Developer @ NAVER Corp | Designer @ HONGIK Univ.

0개의 댓글