如何使用gnu'date'命令将自定义日期格式转换为备用格式?

时间:2013-01-08 17:24:10

标签: shell date

我有一个字符串,其中包含用日语编写的自定义日期格式:2013年1月8日 20時19分。使用osx的date命令,我可以使用以下命令将其转换为其他格式:

timestamp="2013年1月8日 20時19分"
date -j -f "%Y年%m月%d日 %H時%M分" "$timestamp" +"%F %R"

在搜索时我发现了this question helpful,但在gnu date时它最终没有帮助。命令gdate -d "2013年1月8日 20時19分" +"%F %R"无法说明它不了解日期格式。 -d标志允许一些简单的格式,但我如何应用更激进的自定义格式并转换日期?我是不是自己在shell中使用字符串操作解析字符串?

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

您可能需要修改一些环境变量(例如:TZLC_ALL等)。

请参阅this page showing you most of the common environnement variables, and their meanings

尝试一些:你可以在命令本身之前将它们放在同一行上,强制值在以下命令的持续时间内更改

TZ=.... LC_LANG=..... date -d .......

将调用date -d ....,并将2个环境变量TZLC_LANG设置为临时值。

一些有趣的指针(我现在无法判断是否一个程序将把任何语言环境的日期作为输入并将其转换为相关的Epoch或Unix时间戳... BUt似乎希望跟随(看起来非常标准)在线文档的踪迹:

http://pubs.opengroup.org/onlinepubs/9699919799/utilities/date.html

http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html#tag_08_02

与其他许多人谈论:

LC_TIME
    This variable shall determine the locale category for date and time formatting information. It affects the behavior of the time functions in strftime(). Additional semantics of this variable, if any, are implementation-defined.

指向:http://pubs.opengroup.org/onlinepubs/9699919799/functions/getdate.html

在中间说:

The match between the template and input specification performed by getdate() shall be case-insensitive.

The month and weekday names can consist of any combination of upper and lowercase letters. The process can request that the input date or time specification be in a specific language by setting the LC_TIME category (see setlocale ).

并指向:http://pubs.opengroup.org/onlinepubs/9699919799/functions/setlocale.html

...祝你读书愉快!让我们知道你找到了什么!

答案 1 :(得分:1)

我终于借助coreutils mailing list来解决这个问题。但是,他们给出的例子使用perl。它们特别依赖于POSIX :: strptime模块,该模块没有标准的perl安装。因此,我用python解决了这个问题,它有time模块。这个模块应该在python2和python3的大多数安装中都可用。

以下是以编程方式使用它的方法:

Python解决方案:

$ timestamp='2013年1月8日 20時19分'
$ time_format='%Y年%m月%d日 %H時%M分'
$ gdate -u -R -d "$(python -c 'import sys; from time import strptime; t=strptime(sys.argv[-1],"'$time_format'"); print("%d-%d-%d %d:%d"%(t.tm_year,t.tm_mon,t.tm_mday,t.tm_hour,t.tm_min))' $timestamp)"
Tue, 08 Jan 2013 20:19:00 +0000

这适用于python2和python3。您可以根据需要替换任何时间戳和格式。

Perl解决方案

为了记录我在coreutils上给出的答案,perl解决方案是这样的(需要POSIX::strptime

$ gdate -u -R -d "$(perl -MPOSIX::strptime -le 'my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = POSIX::strptime("$ARGV[0]","%Y年%m月%d日 %H時%M分");$year+=1900;$mon+=1;printf("%04d-%02d-%02d %0d:%02d\n",$year,$mon,$mday,$hour,$min);' "2013年1月8日 20時19分")"