How to use strftime for datetime? - ruby

Here is the date-time input
Puts Time.parse("2021-06-26 12:30:35")
Expected output:
26-06-2021 12:30:35

There is difference using in parsing and strptime DateTime functions. Parsing the date time string can gives same input datetime as output shown in example 1. Where strptime is nothing but string previous time it gives datetime inputs as output with timezone shown in example 2 and it follows some rules like Datetime formats as shown in examples 3, which throws an error.
Example 1:
INPUT :
DateTime.parse("02-08-2021 15:20:00").strftime("%d-%m-%Y %H:%M:%S")
OUTPUT :
02-08-2021 15:20:00
Example:2
INPUT :
DateTime.strptime('02-08-2021 15:20:00', '%d-%m-%Y %H:%M:%S')
OUTPUT :
2021-08-02T12:30:35+00:00
Example 3:
INPUT :
DateTime.strptime('02-08-2021 12:30:35', '%Y-%m-%d %H:%M:%S')
OUTPUT:
Date::ERROR

Related

Python datetime function - one pending aspect still from my earlier question

Earlier someone answered my question on Python's datetime function which I am grateful to. However my followup comment/ question remains unanswered. Please help.
My followup question:
Thank you so much. Your answer helped. It works. However when you give 2 digit year with %y and you try to print the year with date.year, it prints prefix of 20xx (e.g. 2023 in my example below). If I wanted it to print 19xx what should I do?
Original question:
datetime.strptime not working as portrayed widely. Using Python 3.11
I see several posts talking about datetime.datetime.strptime that can be used to convert date string '12/13/23' to a datetime object. This doesn't work for me.
import datetime dt = datetime.datetime.strptime('12/13/2023', "%m/%d/%y") produces error as follows
Traceback (most recent call last): File "C:\Users\User\IdeaProjects\FirstTest\Scratchpad.py", line 3, in dt = datetime.datetime.strptime('12/13/2023', "%m/%d/%y") ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib_strptime.py", line 568, in _strptime_datetime tt, fraction, gmtoff_fraction = _strptime(data_string, format) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib_strptime.py", line 352, in _strptime raise ValueError("unconverted data remains: %s" % ValueError: unconverted data remains: 64
Many people show the above code with output working as 2023-12-13 as a datetime object. Doesn't work for me
I was expecting dt.month() to return the month and print(dt) to print yyyy-mm-dd
Answer:
Your code doesn't show the same code that you're running as your traceback.
Your code, which works:
dt = datetime.datetime.strptime('12/13/23', "%m/%d/%y")
Your traceback, which doesn't work:
dt = datetime.datetime.strptime('12/13/2023', "%m/%d/%y")
The traceback is correct to produce an error here, the format string you've given is not valid for the date string you've given. %y parse 2-digit year, and 2023 is not a 2-digit year, you need %Y if you want to parse a 4-digit year.

Hanami validate year less than X

I want to check that a date object I have in a validator.rb file has a year field that is less than the year 10000.
required(:my_date_object).maybe(
:date?,
lt?: '10000-01-01'
)
When running system tests, the following error shows up:
ArgumentError:
comparison of Date with String failed
Should I look into converting the date field into a string using to_s or something similar and then doing a regexp format check? Or is there a more straightforward way of checking that the date is less than the year 10000?
You need to create a Date for the lt?.
You can write it like follows:
required(:my_date_object) { lt?(Date.new(10000, 1, 1)) }

Changing the format from a mySQL datetime format to a different type in ruby?

I am attempting to change an SQL datetime variable (2016-06-09 14:29:34) into a format that looks like this (00:00_20160601). I have tried to follow a couple of SO questions that will allow me to format a Time object.
This is what I have done so far:
start_datetime = "2016-06-09 14:29:34"
t =Time.new(start_datetime)
t.strftime("%H:%M_%Y%d%m")
This results in the time being formatted to 2016-01-01 00:00:00 +0000, which is obviously not what I want. I was wondering if someone could help me format the datetime object the way I specified?
You can do this with DateTime:
require 'datetime'
DateTime.parse("2016-06-09 14:29:34").strftime("%H:%M_%Y%d%m")
#=> "14:29_20160906"
The format you're feeding in is basically ISO-8601 so it's parsed by default.
Feeding that value into Time.new is completely incorrect. The first argument there is the year, the rest have to be supplied separately. That's why you get 2016-01-01, since everything else comes out as defaults.
Time.new is converting automatically and the result of "2016-06-09 14:29:34".to_i is 2016.
It's not entirely clear why your day value changes from 09 in the input to 01 in the desired output, so I'll use the normal thing and output the same as was input:
require 'time'
start_datetime = "2016-06-09 14:29:34"
t = Time.strptime(start_datetime, '%Y-%m-%d %H:%M:%S')
t.strftime('00:00_%Y%m%d') # => "00:00_20160609"
Since the hours and minutes are being thrown away there are a couple of other ways to go about this.
Ignore the hours and minutes when parsing:
t = Time.strptime(start_datetime, '%Y-%m-%d')
Or use a Date object instead of a Time object:
require 'date'
start_datetime = "2016-06-09 14:29:34"
t = Date.strptime(start_datetime, '%Y-%m-%d')
t.strftime('00:00_%Y%m%d') # => "00:00_20160609"

How to split the string obtained from "Time.now" in ruby

A=Time.now
gives following output:
2012:05:18 12:20:50 +0530
I want to form a string like "May 18 , 2012". I tried changing A to string which was not possible. How can I achieve this?
Time.now.strftime('%b %e , %Y')
More info.
You can have a look at the Time Class, and method strftime.
It formats time according to the directives in the given format string.
http://www.ruby-doc.org/core-1.9.3/Time.html#method-i-strftime
For your current problem:
Time.now.strftime("%b %d, %Y")

Convert RSS pubDate Date to MM-DD-YY HH:MM

I have a string, the value of this string is an rss date. I want to convert the value of this string / the rss date into another format (MM-DD-YY HH:MM). Any ideas how to do this?
This is an extract of what I got so far...
#!/usr/bin/env ruby
require 'rss/2.0'
require 'rss/content'
[...]
date = rss.items[i].pubDate
date = #Here I want to convert the date
puts date
[...]
Use Date.parse to get a Date object from a string and then Date#strftime to format it correctly.
http://www.ruby-doc.org/stdlib-1.9.3/libdoc/date/rdoc/Date.html#method-c-parse
http://www.ruby-doc.org/stdlib-1.9.3/libdoc/date/rdoc/Date.html#method-i-strftime
Here's a strftime example:
Time.now.strftime("%m-%d-%Y %H:%M") #=> "03-27-2012 12:03

Resources