タイムスタンプは、特定のイベントがいつ発生したかを見つけるために使用される一連の文字またはエンコードされた情報であり、通常、その日の日付と時刻を数分の一秒の精度で示します。この記事では、その方法を学びます Pythonで現在のタイムスタンプを取得する 。 Python で現在のタイムスタンプを取得するにはさまざまな方法があります。モジュールの関数を使用できます。 時間、日時 そして カレンダー 。 1. モジュール時間の使用: の 時間 モジュールはさまざまな時間関連の関数を提供します。関数 time は、エポックからの時間を浮動小数点数として秒単位で返します。エポックは時間の開始点として定義され、プラットフォームに依存します。
Syntax: time.time() Parameters: NA Return: floating point number expressed in seconds.>
Python3
# using time module> import> time> # ts stores the time in seconds> ts>=> time.time()> # print the current timestamp> print>(ts)> |
>
>
出力:
1594819641.9622827>
2. モジュール datetime を使用する: の 日付時刻 モジュールは、日付と時刻を操作するためのクラスを提供します。日付と時刻の算術演算はサポートされていますが、実装の目標は、出力の書式設定と操作のための効率的な属性抽出です。エポックからの秒数を返す関数 datetime.datetime.now。
Syntax: datetime.now() Parameters: tz (time zone) which is optional. Return: the current local date and time.>
Python3
# using datetime module> import> datetime;> # ct stores current time> ct>=> datetime.datetime.now()> print>('current time:>->', ct)> # ts store timestamp of current time> ts>=> ct.timestamp()> print>('timestamp:>->', ts)> |
>
>
出力:
current time:- 2020-07-15 14:30:26.159446 timestamp:- 1594823426.159446>
3. モジュールカレンダーの使用: 複数のモジュールの複数の関数を組み合わせてタイムスタンプを取得することもできます。ここでは、関数 Calendar.timegm を使用して、現在の時刻を表すタプルを変換します。
Javaループ
Syntax: calendar.timegm(tuple) Parameters: takes a time tuple such as returned by the gmtime() function in the time module. Return: the corresponding Unix timestamp value.>
Python3
# using calendar module> # using time module> import> calendar;> import> time;> # gmt stores current gmtime> gmt>=> time.gmtime()> print>('gmt:>->', gmt)> # ts stores timestamp> ts>=> calendar.timegm(gmt)> print>('timestamp:>->', ts)> |
>
>
出力:
gmt:- time.struct_time(tm_year=2020, tm_mon=7, tm_mday=15, tm_hour=19, tm_min=21, tm_sec=6, tm_wday=2, tm_yday=197, tm_isdst=0) タイムスタンプ:- 1594840866