如何将 Strftime 转换为 Ruby 中的字符串?

How to convert Strftime into string in Ruby?

我想把这个strftime解析成一个字符串,然后把day变量隔离出来就行了。

 '2015-04-15T11:15:34'

我知道在 python 中,你可以这样做:

 datetime.strptime(element, "%Y-%m-%dT%H:%M:%S")

导入如下内容后:

 from datetime import datetime
 from datetime import timedelta

Ruby 中是否有模块或函数可以有效地执行此操作?

是的。它也被称为strptimehttp://ruby-doc.org/stdlib-2.1.1/libdoc/date/rdoc/DateTime.html#method-c-strptime

Parses the given representation of date and time with the given template, and creates a date object. strptime does not support specification of flags and width unlike strftime.

DateTime.strptime('2001-02-03T04:05:06+07:00', '%Y-%m-%dT%H:%M:%S%z') #=> #<DateTime: 2001-02-03T04:05:06+07:00 ...>

包含所需的 date 库后,您可以对生成的 DateTime 对象调用 #day 以获取日期。例如

irb(main):016:0> require 'date'
=> true
irb(main):017:0> date = DateTime.strptime('2015-04-15T11:15:34', "%Y-%m-%dT%H:%M:%S")
=> #<DateTime: 2015-04-15T11:15:34+00:00 ((2457128j,40534s,0n),+0s,2299161j)>
irb(main):018:0> date.day
=> 15

如果您知道格式是 iso8601,您可以使用 DateTime.iso8601,否则您可以使用 DateTime.parse,它也处理其他一些约定。

2.2.1 :001 > require 'date'
 => true 
2.2.1 :002 > dt = DateTime.parse('2015-04-15T11:15:34')
 => #<DateTime: 2015-04-15T11:15:34+00:00 ((2457128j,40534s,0n),+0s,2299161j)> 
2.2.1 :003 > dt.year
 => 2015 
2.2.1 :004 > dt.month
 => 4 
2.2.1 :005 > dt.day
 => 15 
2.2.1 :006 > dt.hour
 => 11 
2.2.1 :007 > dt.zone
 => "+00:00"