使用舍入毫秒 Bash Shell 脚本从时间戳获取格式化日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16036763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 23:36:10  来源:igfitidea点击:

Get Formatted Date From Timestamp With Rounded Milliseconds Bash Shell Script

bashdatetimestamp

提问by StuStirling

I need to get a date in a specific format but can't work out how to do it.

我需要获取特定格式的日期,但不知道如何去做。

Here is how I'm getting the date at the moment.

这是我目前获取日期的方式。

date -r "$timestamp" +'%Y-%m-%dT%H:%M:%S.s'

However the issue is the milliseconds has too many digits for the format I need. I need the milliseconds to be limited to 3 digits.

然而问题是毫秒对于我需要的格式有太多的数字。我需要将毫秒限制为 3 位数字。

Any idea how I can do such a thing?

知道我怎么能做这样的事情吗?

Current Workaround

当前的解决方法

Not accurate but it works. I calculate the milliseconds afterwards and then just take the first three characters of the string. Obviously this doesn't take into account round up.

不准确,但它有效。之后我计算毫秒,然后只取字符串的前三个字符。显然,这并没有考虑到四舍五入。

date_string_one=`date -r "$timestamp" +'%Y-%m-%dT%H:%M:%S.'`
date_string_milli=`date -r "$timestamp" +'%s'`
date_string="$date_string_one"`printf "%.3s" "$date_string_milli"`

回答by Joe

You may simply use %3Nto truncate the nanoseconds to the 3 most significant digits:

您可以简单地使用%3N将纳秒截断为 3 个最重要的数字:

$ date +"%Y-%m-%d %H:%M:%S,%3N"
2014-01-08 16:00:12,746

or

或者

$ date +"%F %T,%3N"
2014-01-08 16:00:12,746

testet with ?GNU bash, Version 4.2.25(1)-release (i686-pc-linux-gnu)?

testet 与 ?GNU bash,版本 4.2.25(1)-release (i686-pc-linux-gnu)?

But be aware, that %N may not implemented depending on your target system or bash version. Tested on an embedded system ?GNU bash, version 4.2.37(2)-release (arm-buildroot-linux-gnueabi)? there was no %N:

但请注意,根据您的目标系统或 bash 版本,%N 可能无法实现。在嵌入式系统上测试?GNU bash,版本 4.2.37(2)-release (arm-buildroot-linux-gnueabi)?没有%N

date +"%F %T,%N"
2014-01-08 16:44:47,%N

回答by Iamiuru

Million ways to do this.. one simple way is to remove the trailing numbers...

百万种方法来做到这一点.. 一种简单的方法是删除尾随数字...

date +'%Y-%m-%d %H:%M:%S.%N' | sed 's/[0-9][0-9][0-9][0-9][0-9][0-9]$//g'

or

或者

date +'%Y-%m-%d %H:%M:%S.%N' | sed 's/......$//g'

回答by azatar

I can't help offering a "cheap" solution...

我忍不住提供了一个“便宜”的解决方案......

echo $(date +"%Y-%m-%d-%H:%M:%S.")$((RANDOM%1000))

After all, if accuracy is less important than uniqueness, as it is in my case... here you have it.

毕竟,如果准确性不如唯一性那么重要,就像在我的情况下一样......你有它。

回答by cevaris

Best way would be shelling out a python command.

最好的方法是使用 python 命令。

$ python -c "from datetime import datetime; print datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]"
2017-02-15 15:03:03.496

You can then create an alias in you ~/.profile

然后你可以在你里面创建一个别名 ~/.profile

$ alias datetime='python -c python -c "from datetime import datetime;...'

Or even create a shell function

甚至创建一个shell函数

datetime(){
  python -c python -c "from datetime import datetime;...
}

回答by punchoyeah

str="2013-04-05 13:33:53.180"

dateStr1=`date -d "$str" +'%Y-%m-%d %H:%M:%S.%N'`;

echo $dateStr1

dateStr2=`date -d "$dateStr1" +'%s'`

echo $dateStr2

dateStr3="$dateStr2"`echo ${dateStr1:20:3}`

echo $dateStr3

============================

[Output]
2013-04-05 13:33:53.180000000
1365140033
1365140033180

(above consider the datestr in UTC)

(以上考虑UTC中的datestr)

回答by jim mcnamara

One problem: %sis not the date format for milliseconds, it is seconds of the current epoch. %N gives nanoseconds, I do not know of a specified date format for GNU date that gives milliseconds.

一个问题:%s不是毫秒的日期格式,而是当前纪元的秒数​​。%N 给出了纳秒,我不知道给出毫秒的 GNU 日期的指定日期格式。

Try date --helpto see all of the format options.

尝试date --help查看所有格式选项。

回答by William

Can't think of a way to do it without a couple of steps, but this will get you there:

没有几个步骤就想不出一种方法,但这会让你做到:

d=$(date +'%Y-%m-%d %H:%M:%S|%N')
ms=$(( ${d#*|}/1000000 ))
d="${d%|*}.$ms"
echo $d

2013-04-16 08:51:48.874

Since all the components are taken from a single call to date they'll be consistent.

由于迄今为止所有组件都是从单个调用中获取的,因此它们将保持一致。

回答by chepner

Use printfto do the actual formatting; use dateto produce the set of arguments printfneeds to fill the format string.

用于printf进行实际格式化;用于date产生printf需要填充格式字符串的参数集 。

printf '%04d-%02d-%02dT%02d:%02d:%02d.%03d' \
        $(date -r "${timestamp%.*}" +"%Y %m %d %H %M %S")\
        $(( ${timestamp#*.} / 1000 ))

In the above, I assume your timestamp looks something like "blahblahblah.728239". The result is a set of arguments for printflike 2013 04 16 11 03 17 728to produce 2013-04-16T11:03:17.728.

在上面,我假设你的时间戳看起来像“blahblahblah.728239”。结果是一组参数printflike 2013 04 16 11 03 17 728to generate 2013-04-16T11:03:17.728