How can I generate Unix timestamps?

2019-01-29 20:10发布

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?

15条回答
来,给爷笑一个
2楼-- · 2019-01-29 20:41

In Perl:

>> time
=> 1335552733
查看更多
Explosion°爆炸
3楼-- · 2019-01-29 20:42

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
查看更多
The star\"
4楼-- · 2019-01-29 20:43
$ 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.

查看更多
小情绪 Triste *
5楼-- · 2019-01-29 20:44

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.

查看更多
一夜七次
6楼-- · 2019-01-29 20:44

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.

查看更多
甜甜的少女心
7楼-- · 2019-01-29 20:44

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).

查看更多
登录 后发表回答