Parse complex string to carbon date - laravel

I am using Laravel Framework 6.16.0 and want to parse a date with carbon "Dec 14 02:04 PM":
$fillingDate = "Dec 14 02:04 PM";
$filling_Date = Carbon::parse($fillingDate, 'UTC');
// result is only a string "Dec 14 02:04 PM"
When using the above structure I only get the string back. However, I would like to get a Carbon object that gets then formatted to ->format('Y-m-d').
Any suggestions what I am doing wrong?
I appreciate your replies!

You can create carbon object from a string by calling the static function createFromFormat.
In this case:
$fillingDate = "Dec 14 02:04 PM";
$filling_Date = Carbon::createFromFormat("M d g:i A", $fillingDate)
Format characters explained:
M - A short textual representation of a month, three letters
d - Day of the month, 2 digits with leading zeros
g - 12-hour format of an hour without leading zeros
i - Minutes with leading zeros
A - Uppercase Ante meridiem and Post meridiem
More about format characters: PHP documentation

Related

time data doesn't match format specified

I am trying to convert the string to the type of 'datetime' in python. My data match the format, but still get the
'ValueError: time data 11 11 doesn't match format specified'
I am not sure where does the "11 11" in the error come from.
My code is
train_df['date_captured1'] = pd.to_datetime(train_df['date_captured'], format="%Y-%m-%d %H:%M:%S")
Head of data is
print (train_df.date_captured.head())
0 2011-05-13 23:43:18
1 2012-03-17 03:48:44
2 2014-05-11 11:56:46
3 2013-10-06 02:00:00
4 2011-07-12 13:11:16
Name: date_captured, dtype: object
I tried the following by just selecting the first string and running the code with same datetime format. They all work without problem.
dt=train_df['date_captured']
dt1=dt[0]
date = datetime.datetime.strptime(dt1, "%Y-%m-%d %H:%M:%S")
print(date)
2011-05-13 23:43:18
and
dt1=pd.to_datetime(dt1, format='%Y-%m-%d %H:%M:%S')
print (dt1)
2011-05-13 23:43:18
But why wen I using the same format in pd.to_datetime to convert all the data in the column, it comes up with the error above?
Thank you.
I solved it.
train_df['date_time'] = pd.to_datetime(train_df['date_captured'], errors='coerce')
print (train_df[train_df.date_time.isnull()])
I found in line 100372, the date_captured value is '11 11'
category_id date_captured ... height date_time
100372 10 11 11 ... 747 NaT
So the code with errors='coerce' will replace the invalid parsing with NaN.
Thank you.

Checking for time

I have a form field which may have a date and may have a time in it. I need to confirm that both a date and time are present.
<input type="text" name="transdate" ... />
I can use isDate(form.transdate) to check if there is a date, but it does not check if there is a time. I wish there was a isTime() function.
Addendum
The date time fields can be made to have
These fields are concatinated via
date_cat = "#form.trans_date# #form.trans_date_h#:#form.trans_date_m# #form.trans_date_t#";
When I run this code:
cat: #date_cat# isValid(date): #isValid('date', date_cat)# isValid(time): #isValid('time', date_cat)#
I get
cat: 12/05/2018 :24 PM isValid(date): YES isValid(time): YES
Some people hate regular expressions. I love them. Why not just check the concatenated string?
dtRegEx = "^(0[1-9]|1[0-2])/(0[1-9]|[1-2][0-9]|3[0-1])/[1-9][0-9]{3} (0[0-9]|1[0-2]):[0-5][0-9] (am|pm)$";
if (reFind(dtRegEx, date_cat) and isDate(date_cat)) {
// valid datetime
} else {
// invalid datetime
}
RegEx Breakdown
^
string has to start with the whole pattern
(0[1-9]|1[0-2])
month in range from 01 to 09 or 10 to 12
/
date delimiter
(0[1-9]|[1-2][0-9]|3[0-1])
day in range from 01 to 09, 10 to 29 or 30 to 31
/
date delimiter
[1-9][0-9]{3}
year in range from 1000 to 9999
space
space, literally
(0[0-9]|1[0-2])
hour in range from 00 to 09 or 10 to 12
:
time delimiter
[0-5][0-9]
seconds in range from 00 to 59
space
space, again
(am|pm)
the meridiem stuff you guys from US and UK like so much :P
$
string has to end with the whole pattern
Note that the above pattern could still have you end up with invalid day ranges like 02/31/2018, that's why you should still check with isDate().
Here is how I addressed it, I validated the fields before the concatenation
if (form.trans_date_h == "" || form.trans_date_m == "" || form.trans_date_t == "") {
// error handling here
Then did the concatenation
date_cat = "#form.trans_date# #form.trans_date_h#:#form.trans_date_m# #form.trans_date_t#";

Formatting date without lading zero to the day [duplicate]

This question already has answers here:
date format function to display date as "Jan 13 2014"
(3 answers)
Closed 7 years ago.
I writing a code in VBScript, but I cannot get the datetime part right.
I'm using FormatDateTime(now), but the gives not the best result like
FormatDateTime(now)
8-01-2016 9:05:12 becomes 01-08-2016 9:05:12.
28-01-2016 19:01:18 stays 28-01-2016 19:01:18.
Has to be:
8-01-2016 9:05:12
28-01-2016 19:01:18
Is there a way to get both the same?
Try using the format argument of FormatDateTime.
FormatDateTime(now, 2) 'This should return in mm/dd/yy format
More info here.
http://www.w3schools.com/asp/func_formatdatetime.asp
format (Optional) A value that specifies the date/time format to use
Can take the following values:
0 = vbGeneralDate - Default. Returns date: mm/dd/yy and time if
specified: hh:mm:ss PM/AM.
1 = vbLongDate - Returns date: weekday,
monthname, year
2 = vbShortDate - Returns date: mm/dd/yy
3 =
vbLongTime - Returns time: hh:mm:ss PM/AM
4 = vbShortTime - Return
time: hh:mm
This should do what you want.
od = "28-01-2016 19:01:18"
nd = FormatDateTime(od,0)
MsgBox(nd)
Output: 1/28/2016 7:01:18 PM

Rails 4 parse a date in a different language

I have a text_field :birthday_line in my user form, that I need to parse into the user's birthday attribute.
So I'm doing something like this in my User class.
attr_accessor :birthday_line
before_save :set_birthday
def set_birthday
self.birthday = Date.strptime(birthday_line, I18n.translate("date.formats.default")
end
But the problem is that for some reason it gives me an error saying Invalid date when I try to pass in a string 27 января 1987 г. wich should be parsed to 1987-01-27.
The format and month names in my config/locales/ru.yml
ru:
date:
formats:
default: "%d %B %Y г."
month_names: [~, января, февраля, марта, апреля, мая, июня, июля, августа, сентября, октября, ноября, декабря]
seem to be correct.
Date.parse also doesn't help, it just parses the day number (27) and puts the month and year to todays date (so it'll be September 27 2013 instead of January 27 1987).
I had the same problem and what I can suggest:
string_with_cyrillic_date = '27 Января 1987'
1)create array of arrays like this
months = [["января", "Jan"], ["февраля", "Feb"], ["марта", "Mar"], ["апреля", "Apr"], ["мая", "May"], ["июня", "Jun"], ["июля", "Jul"], ["августа", "Aug"], ["сентября", "Sep"], ["октября", "Oct"], ["ноября", "Nov"], ["декабря", "Dec"]]
2) Now you can iterate this and find your cyrillic month:
months.each do |cyrillic_month, latin_month|
if string_with_cyrillic_date.match cyrillic_month
DateTime.parse string_with_cyrillic_date.gsub!(/#{cyrillic_month}/, latin_month)
end
end
And now you will receive the date that you expect
27 Jan 1987

Parsing date from text using Ruby

I'm trying to figure out how to extract dates from unstructured text using Ruby.
For example, I'd like to parse the date out of this string "Applications started after 12:00 A.M. Midnight (EST) February 1, 2010 will not be considered."
Any suggestions?
Try Chronic (http://chronic.rubyforge.org/) it might be able to parse that otherwise you're going to have to use Date.strptime.
Assuming you just want dates and not datetimes:
require 'date'
string = "Applications started after 12:00 A.M. Midnight (EST) February 1, 2010 will not be considered."
r = /(January|February|March|April|May|June|July|August|September|October|November|December) (\d+{1,2}), (\d{4})/
if string[r]
date =Date.parse(string[r])
puts date
end
Also you can try a gem that can help find date in string.
Exapmle:
input = 'circa 1960 and full date 07 Jun 1941'
dates_from_string = DatesFromString.new
dates_from_string.get_structure(input)
#=> return
# [{:type=>:year, :value=>"1960", :distance=>4, :key_words=>[]},
# {:type=>:day, :value=>"07", :distance=>1, :key_words=>[]},
# {:type=>:month, :value=>"06", :distance=>1, :key_words=>[]},
# {:type=>:year, :value=>"1941", :distance=>0, :key_words=>[]}]

Resources