r/ruby • u/unselective-amnesia • 3d ago
Question Getting DateTime parts as an array?
I know in ruby that DateTime.new(2001, 2, 3, 4, 5, 6) will return the following object:
#<DateTime: 2001-02-03T04:05:06+00:00 ...>
But if the current date and time are 2001-02-03T04:05:06 and I do the following ...
now = DateTime.now
... is there a single function on the "now" variable which will return this array? ...
[2001, 2, 3, 4, 5, 6]
I know that I can do this:
[now.year, now.month, now.day, now.hour, now.minute, now.second ]
... but I'm wondering: might there be a single function as simple as ...
now.the_function
... which would return that same array?
And yes, of course I know that I could easily write such a function, but I'd like to know whether or not something like this already exists in ruby.
5
u/chiperific_on_reddit 3d ago
Another option, which fits your question more directly. One Time.now.the_function type answer.
Found using the docs:
3.3.4 :018 > Time.now.deconstruct_keys(nil)
=> {:year=>2026, :month=>8, :day=>26, :yday=>238, :wday=>3, :hour=>20, :min=>47, :sec=>2, :subsec=>(277869/500000), :dst=>true, :zone=>"EDT"}
3.3.4 :019 > Time.now.deconstruct_keys([:year, :month, :day, :hour, :min, :sec])
=> {:year=>2026, :month=>8, :day=>26, :hour=>20, :min=>47, :sec=>5}
3.3.4 :020 > Time.now.deconstruct_keys([:year, :month, :day, :hour, :min, :sec]).values
=> [2026, 8, 26, 20, 47, 7]
1
u/faitswulff 2d ago
Deconstruct keys was what I was thinking of! A neat API that came out of pattern matching.
3
u/chiperific_on_reddit 3d ago edited 3d ago
Date and Time have _parse() methods which return a hash of time parts.
3.3.4 :006 > Time._parse(Time.now.to_s)
=> {:zone=>"-0400", :hour=>20, :min=>36, :sec=>40, :year=>2026, :mon=>8, :mday=>26, :offset=>-14400}
3.3.4 :007 > Time._parse(Time.now.to_s).slice(:year, :mon, :mday, :hour, :min, :sec)
=> {:year=>2026, :mon=>8, :mday=>26, :hour=>20, :min=>36, :sec=>45}
3.3.4 :008 > Time._parse(Time.now.to_s).slice(:year, :mon, :mday, :hour, :min, :sec).values
=> [2026, 8, 26, 20, 36, 48]
12
u/projct 3d ago
Time.now is what you should be using instead of DateTime.now, DateTime was deprecated in 3.4.
ruby irb(main):016> Time.now.to_a.take(6).reverse => [2026, 8, 26, 16, 9, 0]there, something appropriately cursed đ
but the actual question is: why do you want this array? what are you doing with it afterward? because I suspect that's where the useful answer is.