LoginSignup
0
1

More than 5 years have passed since last update.

時刻をプログラムで扱いたい

Last updated at Posted at 2018-09-22
1 / 9

初投稿。知り合いには気づかれたくないが、個人のメモを今後はこちらに移していこう。

日時時刻の扱い

  • 2018/09/20 01:23:45.678901 のように、年月日時分秒で時刻を計算で使用したい
  • CSVファイルに保存する
  • python pandas では pd.to_datetime で変換できる。dtype は datetime64[ns] で保持。
  • C/C++ではtime_tで保持。Cではprintfやstrftime() で、C++ では std::put_time で time_t を指定形式で書ける。

テキストファイルでの保存

次のようなCSVファイル (log.csv)に保存されているとする。
t,val
2018/09/10 11:22:33.4,1.0
2000/1/2 03:04:55.666,2.0


python で読む

test.py
import pandas as pd
df = pd.read_csv('log.csv')
df['t'] = pd.to_datetime(df.ts)
print(df.ts)
print(df.t)

datetime64[ns]

最初のdf.ts はdtype が object である。

0    2018/09/10 11:22:33.4
1    2000/1/2 03:04:55.666
Name: ts, dtype: object

pd.to_datetime を用いると、dtypeが datetime64[ns] になる。

0   2018-09-10 11:22:33.400000
1   2000-01-02 03:04:55.666000
Name: t, dtype: datetime64[ns]

time.h の time_t

test_time_print.c
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
int main() {
    struct timeval ct;
    struct tm *t;

    gettimeofday( &ct, NULL );
    t = localtime(&ct.tv_sec);

    printf("%04d-%02d-%02d %02d:%02d:%02d.%03d\n",
                t->tm_year+1900,
                t->tm_mon+1,
                t->tm_mday,
                t->tm_hour,
                t->tm_min,
                t->tm_sec,
                (int)ct.tv_usec/1000
        );
    return 0;
}

timt_t in strftime


  char buffer[256];
  strftime(buffer, sizeof(buffer), "%a %b %d %H:%M:%S %Y", &your_tm);

strftime for C++: put_time


#include <iostream>
#include <iomanip>
#include <ctime>
int main()
{
    std::time_t t = std::time(nullptr);
    std::tm tm = *std::localtime(&t);
    std::cout.imbue(std::locale("ru_RU.utf8"));
    std::cout << "ru_RU: " << std::put_time(&tm, "%c %Z") << '\n';
    std::cout.imbue(std::locale("ja_JP.utf8"));
    std::cout << "ja_JP: " << std::put_time(&tm, "%c %Z") << '\n';
}

備考

  • うるう秒(leap second)の情報って、どうのように更新されるのかな。
  • GPS week, time of week との変換はできるのだが、簡単なGUIを作りたい。
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1