如何用Perl解析相对日期? [英] How can I parse relative dates with Perl?

查看:113
本文介绍了如何用Perl解析相对日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很想知道是否有一个模块来解析Perl中的人性化格式日期。我的意思是像明天,星期二,下周,1小时前这样的事情。



我对CPAN的研究表明,没有这样的模块,那么你将如何去创造一个? NLP是这个的顶端。

解决方案

Date :: Manip 完全是这样的。



这是一个示例程序:

 #!/ usr / bin / perl 

use strict;
使用Date :: Manip;

while(< DATA>)
{
chomp;
print UnixDate($ _,%Y-%m-%d%H:%M:%S),($ _)\\\
;
}

__DATA__
今天
昨天
明天
上周二
下周二
1小时前

哪些导致以下输出:

  2008-11-17 15:21:04(今天)
2008-11-16 15:21:04(昨天)
2008- 11-18 15:21:04(明天)
2008-11-11 00:00:00(上周二)
2008-11-18 00:00:00(下周二)
2008-11-17 14:21:04(1小时前)
2008-11-24 00:00:00(下周)

UnixDate是由 Date :: Manip 提供的函数之一,第一个参数是任何格式的日期/时间该模块支持,第二个参数描述如何格式化日期/时间。还有其他功能,只是解析这些人类日期,而不需要格式化它们,用于delta计算等。


I'd love to know if there is a module to parse "human formatted" dates in Perl. I mean things like "tomorrow", "Tuesday", "next week", "1 hour ago".

My research with CPAN suggest that there is no such module, so how would you go about creating one? NLP is way over the top for this.

解决方案

Date::Manip does exactly this.

Here is an example program:

#!/usr/bin/perl

use strict;
use Date::Manip;

while (<DATA>)
{
  chomp;
  print UnixDate($_, "%Y-%m-%d %H:%M:%S"),  " ($_)\n";
}

__DATA__
today
yesterday
tomorrow
last Tuesday
next Tuesday
1 hour ago
next week

Which results in the following output:

2008-11-17 15:21:04 (today)
2008-11-16 15:21:04 (yesterday)
2008-11-18 15:21:04 (tomorrow)
2008-11-11 00:00:00 (last Tuesday)
2008-11-18 00:00:00 (next Tuesday)
2008-11-17 14:21:04 (1 hour ago)
2008-11-24 00:00:00 (next week)

UnixDate is one of the functions provided by Date::Manip, the first argument is a date/time in any format that the module supports, the second argument describes how to format the date/time. There are other functions that just parse these "human" dates, without formatting them, to be used in delta calculations, etc.

这篇关于如何用Perl解析相对日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆