如何生成 Unix 时间戳?

发布于 2024-07-30 05:43:31 字数 382 浏览 8 评论 0原文

相关问题是"Datetime To Unix timestamp",但这个问题更笼统。

我需要 Unix 时间戳来解决我的最后一个问题。 a> 我的兴趣是 Python、Ruby 和 Haskell,但也欢迎其他方法。

生成 Unix 时间戳的最简单方法是什么?

Related question is "Datetime To Unix timestamp", but this question is more general.

I need Unix timestamps to solve my last question. My interests are Python, Ruby and Haskell, but other approaches are welcome.

What is the easiest way to generate Unix timestamps?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(19

兮颜 2024-08-06 05:43:31

nawk:

$ nawk 'BEGIN{print srand()}'
  • 甚至可以在旧版本的 Solaris 和可能其他未实现“日期 +%s”的 UNIX 系统上工作
  • 不适用于 Linux 和其他 posix 工具已被 GNU 版本替换的发行版(nawk -> gawk 等)
  • 相当不直观,但绝对有趣:-)

nawk:

$ nawk 'BEGIN{print srand()}'
  • Works even on old versions of Solaris and probably other UNIX systems, where '''date +%s''' isn't implemented
  • Doesn't work on Linux and other distros where the posix tools have been replaced with the GNU versions (nawk -> gawk etc.)
  • Pretty unintuitive but definitelly amusing :-)
闻呓 2024-08-06 05:43:31

在 Linux 或 MacOS 中,您可以使用:

date +%s

其中

  • +%s,自 1970-01-01 00:00:00 UTC 以来的秒数。 (GNU Coreutils 8.24 日期手册)

示例输出现在为 1454000043。

In Linux or MacOS you can use:

date +%s

where

  • +%s, seconds since 1970-01-01 00:00:00 UTC. (GNU Coreutils 8.24 Date manual)

Example output now 1454000043.

近箐 2024-08-06 05:43:31

在红宝石中:

>> Time.now.to_i
=> 1248933648

in Ruby:

>> Time.now.to_i
=> 1248933648
过去的过去 2024-08-06 05:43:31

在 Perl 中:

>> time
=> 1335552733

In Perl:

>> time
=> 1335552733
浅沫记忆 2024-08-06 05:43:31
$ date +%s.%N

其中(GNU Coreutils 8.24 日期手册)

  • +%s,自 1970-01-01 00:00:00 UTC 以来的秒数
  • +%N,纳秒 (000000000..999999999)自纪元以来

示例输出现在1454000043.704350695
我注意到date的BSD手册没有包含关于+%s标志的精确解释。

$ date +%s.%N

where (GNU Coreutils 8.24 Date manual)

  • +%s, seconds since 1970-01-01 00:00:00 UTC
  • +%N, nanoseconds (000000000..999999999) since epoch

Example output now 1454000043.704350695.
I noticed that BSD manual of date did not include precise explanation about the flag +%s.

苏佲洛 2024-08-06 05:43:31

在 python 中添加以下行来获取时间戳:

>>> import time
>>> time.time()
1335906993.995389
>>> int(time.time())
1335906993

In python add the following lines to get a time stamp:

>>> import time
>>> time.time()
1335906993.995389
>>> int(time.time())
1335906993
不美如何 2024-08-06 05:43:31

在 Bash 5 中,有一个新变量:

echo $EPOCHSECONDS

或者如果您想要更高的精度(以微秒为单位):

echo $EPOCHREALTIME

In Bash 5 there's a new variable:

echo $EPOCHSECONDS

Or if you want higher precision (in microseconds):

echo $EPOCHREALTIME
嘿嘿嘿 2024-08-06 05:43:31

unix 的“date”命令的用途非常广泛。

date -j -f "%a %b %d %T %Z %Y" "`date`" "+%s"

获取 date 的输出,该输出将采用 -f 定义的格式,然后以 +%s, 秒的形式打印出来(-j 表示不要尝试设置日期)自纪元以来。

The unix 'date' command is surprisingly versatile.

date -j -f "%a %b %d %T %Z %Y" "`date`" "+%s"

Takes the output of date, which will be in the format defined by -f, and then prints it out (-j says don't attempt to set the date) in the form +%s, seconds since epoch.

漆黑的白昼 2024-08-06 05:43:31

首先,Unix“纪元”或零时间是 1970-01-01 00:00:00Z(意思是 Zulu 或 GMT 或 UTC 时区的 1970 年 1 月 1 日午夜)。 Unix 时间戳是自该时间以来的秒数 - 不考虑闰秒。

在 Perl 中生成当前时间相当容易:

perl -e 'print time, "\n"'

生成与给定日期/时间值相对应的时间则不太容易。 从逻辑上讲,您使用 POSIX 中的 strptime() 函数。 但是,Perl POSIX::strptime 模块(与 POSIX 模块分开)具有签名:

($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = 
                                     POSIX::strptime("string", "Format");

POSIX 模块中的函数 mktime 具有签名:

mktime(sec, min, hour, mday, mon, year, wday = 0, yday = 0, isdst = 0)

因此,如果您知道数据的格式,你可以写一个变体:

perl -MPOSIX -MPOSIX::strptime -e \
    'print mktime(POSIX::strptime("2009-07-30 04:30", "%Y-%m-%d %H:%M")), "\n"'

First of all, the Unix 'epoch' or zero-time is 1970-01-01 00:00:00Z (meaning midnight of 1st January 1970 in the Zulu or GMT or UTC time zone). A Unix time stamp is the number of seconds since that time - not accounting for leap seconds.

Generating the current time in Perl is rather easy:

perl -e 'print time, "\n"'

Generating the time corresponding to a given date/time value is rather less easy. Logically, you use the strptime() function from POSIX. However, the Perl POSIX::strptime module (which is separate from the POSIX module) has the signature:

($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = 
                                     POSIX::strptime("string", "Format");

The function mktime in the POSIX module has the signature:

mktime(sec, min, hour, mday, mon, year, wday = 0, yday = 0, isdst = 0)

So, if you know the format of your data, you could write a variant on:

perl -MPOSIX -MPOSIX::strptime -e \
    'print mktime(POSIX::strptime("2009-07-30 04:30", "%Y-%m-%d %H:%M")), "\n"'
鲜血染红嫁衣 2024-08-06 05:43:31

Haskell

import Data.Time.Clock.POSIX

main :: IO ()
main = print . floor =<< getPOSIXTime

转到

import "time"
t := time.Unix()

C

time(); // in time.h POSIX

// for Windows time.h
#define UNIXTIME(result)   time_t localtime; time(&localtime); struct tm* utctime = gmtime(&localtime); result = mktime(utctime);

in Swift

NSDate().timeIntervalSince1970 // or Date().timeIntervalSince1970

in Haskell

import Data.Time.Clock.POSIX

main :: IO ()
main = print . floor =<< getPOSIXTime

in Go

import "time"
t := time.Unix()

in C

time(); // in time.h POSIX

// for Windows time.h
#define UNIXTIME(result)   time_t localtime; time(&localtime); struct tm* utctime = gmtime(&localtime); result = mktime(utctime);

in Swift

NSDate().timeIntervalSince1970 // or Date().timeIntervalSince1970
篱下浅笙歌 2024-08-06 05:43:31

为了完整起见,PHP:

php -r 'echo time();'

在 BASH 中:

clitime=$(php -r 'echo time();')
echo $clitime

For completeness, PHP:

php -r 'echo time();'

In BASH:

clitime=$(php -r 'echo time();')
echo $clitime
无妨# 2024-08-06 05:43:31

如果我想使用 date 命令打印 utc 日期时间,我需要将 -u 参数与 date 命令一起使用。

示例

date -u

输出

Fri Jun 14 09:00:42 UTC 2019

If I want to print utc date time using date command I need to using -u argument with date command.

Example

date -u

Output

Fri Jun 14 09:00:42 UTC 2019
探春 2024-08-06 05:43:31
public static Int32 GetTimeStamp()
    {
        try
        {
            Int32 unixTimeStamp;
            DateTime currentTime = DateTime.Now;
            DateTime zuluTime = currentTime.ToUniversalTime();
            DateTime unixEpoch = new DateTime(1970, 1, 1);
            unixTimeStamp = (Int32)(zuluTime.Subtract(unixEpoch)).TotalSeconds;
            return unixTimeStamp;
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex);
            return 0;
        }
    }
public static Int32 GetTimeStamp()
    {
        try
        {
            Int32 unixTimeStamp;
            DateTime currentTime = DateTime.Now;
            DateTime zuluTime = currentTime.ToUniversalTime();
            DateTime unixEpoch = new DateTime(1970, 1, 1);
            unixTimeStamp = (Int32)(zuluTime.Subtract(unixEpoch)).TotalSeconds;
            return unixTimeStamp;
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex);
            return 0;
        }
    }
和影子一齐双人舞 2024-08-06 05:43:31

在 Haskell 中...

要将其作为 POSIXTime 类型返回:

import Data.Time.Clock.POSIX
getPOSIXTime

作为整数:

import Data.Time.Clock.POSIX
round `fmap` getPOSIXTime

In Haskell...

To get it back as a POSIXTime type:

import Data.Time.Clock.POSIX
getPOSIXTime

As an integer:

import Data.Time.Clock.POSIX
round `fmap` getPOSIXTime
岛徒 2024-08-06 05:43:31

让我们尝试 JavaScript

var t = Math.floor((new Date().getTime()) / 1000);

...或者更好的是静态方法:

var t = Math.floor(Date.now() / 1000);

在这两种情况下,我除以 1000 来从秒变为毫秒,并使用 Math.floor 来仅表示已经过去的整秒(与. 四舍五入,可能四舍五入为尚未过去的一整秒)。

Let's try JavaScript:

var t = Math.floor((new Date().getTime()) / 1000);

...or even nicer, the static approach:

var t = Math.floor(Date.now() / 1000);

In both cases I divide by 1000 to go from seconds to millis and I use Math.floor to only represent whole seconds that have passed (vs. rounding, which might round up to a whole second that hasn't passed yet).

偏爱你一生 2024-08-06 05:43:31

对于类 Unix 环境,以下内容将起作用。

# Current UNIXTIME
unixtime() {
  datetime2unixtime "$(date -u +'%Y-%m-%d %H:%M:%S')"
}

# From DateTime(%Y-%m-%d %H:%M:%S)to UNIXTIME
datetime2unixtime() {
  set -- "${1%% *}" "${1##* }"
  set -- "${1%%-*}" "${1#*-}" "${2%%:*}" "${2#*:}"
  set -- "$1" "${2%%-*}" "${2#*-}" "$3" "${4%%:*}" "${4#*:}"
  set -- "$1" "${2#0}" "${3#0}" "${4#0}" "${5#0}" "${6#0}"
  [ "$2" -lt 3 ] && set -- $(( $1-1 )) $(( $2+12 )) "$3" "$4" "$5" "$6"
  set -- $(( (365*$1)+($1/4)-($1/100)+($1/400) )) "$2" "$3" "$4" "$5" "$6"
  set -- "$1" $(( (306*($2+1)/10)-428 )) "$3" "$4" "$5" "$6"
  set -- $(( ($1+$2+$3-719163)*86400+$4*3600+$5*60+$6 ))
  echo "$1"
}

# From UNIXTIME to DateTime format(%Y-%m-%d %H:%M:%S)
unixtime2datetime() {
  set -- $(( $1%86400 )) $(( $1/86400+719468 )) 146097 36524 1461
  set -- "$1" "$2" $(( $2-(($2+2+3*$2/$3)/$5)+($2-$2/$3)/$4-(($2+1)/$3) ))
  set -- "$1" "$2" $(( $3/365 ))
  set -- "$@" $(( $2-( (365*$3)+($3/4)-($3/100)+($3/400) ) ))
  set -- "$@" $(( ($4-($4+20)/50)/30 ))
  set -- "$@" $(( 12*$3+$5+2 ))
  set -- "$1" $(( $6/12 )) $(( $6%12+1 )) $(( $4-(30*$5+3*($5+4)/5-2)+1 ))
  set -- "$2" "$3" "$4" $(( $1/3600 )) $(( $1%3600 ))
  set -- "$1" "$2" "$3" "$4" $(( $5/60 )) $(( $5%60 ))
  printf "%04d-%02d-%02d %02d:%02d:%02d\n" "$@"
}

# Examples
unixtime # => Current UNIXTIME
date +%s # Linux command

datetime2unixtime "2020-07-01 09:03:13" # => 1593594193
date -u +%s --date "2020-07-01 09:03:13" # Linux command

unixtime2datetime "1593594193" # => 2020-07-01 09:03:13
date -u --date @1593594193 +"%Y-%m-%d %H:%M:%S" # Linux command

https://tech.io/snippet/a3dWEQY

For Unix-like environment the following will work.

# Current UNIXTIME
unixtime() {
  datetime2unixtime "$(date -u +'%Y-%m-%d %H:%M:%S')"
}

# From DateTime(%Y-%m-%d %H:%M:%S)to UNIXTIME
datetime2unixtime() {
  set -- "${1%% *}" "${1##* }"
  set -- "${1%%-*}" "${1#*-}" "${2%%:*}" "${2#*:}"
  set -- "$1" "${2%%-*}" "${2#*-}" "$3" "${4%%:*}" "${4#*:}"
  set -- "$1" "${2#0}" "${3#0}" "${4#0}" "${5#0}" "${6#0}"
  [ "$2" -lt 3 ] && set -- $(( $1-1 )) $(( $2+12 )) "$3" "$4" "$5" "$6"
  set -- $(( (365*$1)+($1/4)-($1/100)+($1/400) )) "$2" "$3" "$4" "$5" "$6"
  set -- "$1" $(( (306*($2+1)/10)-428 )) "$3" "$4" "$5" "$6"
  set -- $(( ($1+$2+$3-719163)*86400+$4*3600+$5*60+$6 ))
  echo "$1"
}

# From UNIXTIME to DateTime format(%Y-%m-%d %H:%M:%S)
unixtime2datetime() {
  set -- $(( $1%86400 )) $(( $1/86400+719468 )) 146097 36524 1461
  set -- "$1" "$2" $(( $2-(($2+2+3*$2/$3)/$5)+($2-$2/$3)/$4-(($2+1)/$3) ))
  set -- "$1" "$2" $(( $3/365 ))
  set -- "$@" $(( $2-( (365*$3)+($3/4)-($3/100)+($3/400) ) ))
  set -- "$@" $(( ($4-($4+20)/50)/30 ))
  set -- "$@" $(( 12*$3+$5+2 ))
  set -- "$1" $(( $6/12 )) $(( $6%12+1 )) $(( $4-(30*$5+3*($5+4)/5-2)+1 ))
  set -- "$2" "$3" "$4" $(( $1/3600 )) $(( $1%3600 ))
  set -- "$1" "$2" "$3" "$4" $(( $5/60 )) $(( $5%60 ))
  printf "%04d-%02d-%02d %02d:%02d:%02d\n" "$@"
}

# Examples
unixtime # => Current UNIXTIME
date +%s # Linux command

datetime2unixtime "2020-07-01 09:03:13" # => 1593594193
date -u +%s --date "2020-07-01 09:03:13" # Linux command

unixtime2datetime "1593594193" # => 2020-07-01 09:03:13
date -u --date @1593594193 +"%Y-%m-%d %H:%M:%S" # Linux command

https://tech.io/snippet/a3dWEQY

萌梦深 2024-08-06 05:43:31

使用 NodeJS,只需打开终端并输入:
node -e "console.log(new Date().getTime())"node -e "console.log( Date.now())"

With NodeJS, just open a terminal and type:
node -e "console.log(new Date().getTime())" or node -e "console.log(Date.now())"

千鲤 2024-08-06 05:43:31

在铁锈中:

use std::time::{SystemTime, UNIX_EPOCH};


fn main() {
    let now = SystemTime::now();
    println!("{}", now.duration_since(UNIX_EPOCH).unwrap().as_secs())
}

In Rust:

use std::time::{SystemTime, UNIX_EPOCH};


fn main() {
    let now = SystemTime::now();
    println!("{}", now.duration_since(UNIX_EPOCH).unwrap().as_secs())
}
仅冇旳回忆 2024-08-06 05:43:31

如果您需要来自 shell 脚本(Bourne 系列:sh、ksh、bash、zsh 等)的 Unix 时间戳,这应该适用于任何 Unix 机器,与其他建议(perl、haskell、ruby、python、GNU date)不同),它基于 POSIX 标准命令和功能。

PATH=`getconf PATH` awk 'BEGIN {srand();print srand()}'

If you need a Unix timestamp from a shell script (Bourne family: sh, ksh, bash, zsh, ...), this should work on any Unix machine as unlike the other suggestions (perl, haskell, ruby, python, GNU date), it is based on a POSIX standard command and feature.

PATH=`getconf PATH` awk 'BEGIN {srand();print srand()}'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文