NSDateFormatter return nil date for specify date strings - nsdate

I am trying to convert a string to date but NSDateFormatter returns nil for a specific date. In the code below all string are converted to Date except for date2 and date7. Any pointers as to what is wrong? Thanks
let date1 = "Jan 01, 1941"
let date2 = "Oct 01, 1941"
let date3 = "Oct 13, 1941"
let date4 = "Sep 30, 1941"
let date5 = "Mar 31, 1941"
let date6 = "Oct 02, 1941"
let date7 = "Oct 01, 1941"
let dateStringFormatter = DateFormatter()
dateStringFormatter.dateFormat = "MMM dd, yyyy" //Using custom
dateStringFormatter.locale = Locale(identifier: "en_US_POSIX")
let date_1 : Date? = dateStringFormatter.date(from: date1)
let date_2 : Date? = dateStringFormatter.date(from: date2)
let date_3 : Date? = dateStringFormatter.date(from: date3)
let date_4 : Date? = dateStringFormatter.date(from: date4)
let date_5 : Date? = dateStringFormatter.date(from: date5)
let date_6 : Date? = dateStringFormatter.date(from: date6)
let date_7 : Date? = dateStringFormatter.date(from: date7)
print("\(String(describing: date_1)),\n\(String(describing: date_2)),\n\(String(describing: date_3)),\n\(String(describing: date_4)),\n\(String(describing: date_5)),\n\(String(describing: date_6)),\n\(String(describing: date_7))")

The above problem can be solved by setting the date property on DateFormatter. The Date can be current system date.

Related

How to extract seconds from datetime.timedelta

I have a list of dates and hours. For each date, I would like to extract only the seconds value.
Here is my script :
import datetime
format_string = "%Y-%m-%d %H:%M"
now = datetime.datetime.now()
date = ['2021-01-29 15:15', '2021-01-29 15:50', '2021-01-29 17:00']
date = [(datetime.datetime.strptime(i, format_string)-now) for i in date]
print(date)
And here is the output :
[datetime.timedelta(seconds=7269, microseconds=211221), datetime.timedelta(seconds=9369, microseconds=211221), datetime.timedelta(seconds=13569, microseconds=211221)]
I just want the seconds for the three elements of the list 'data'
Just change
date = [(datetime.datetime.strptime(i, format_string)-now) for i in date]
To
date = [(datetime.datetime.strptime(i, format_string)-now).seconds for i in date]date = [(datetime.datetime.strptime(i, format_string)-now) for i in date]
It works with :
date = [(datetime.datetime.strptime(i, format_string)-now).seconds for i in date]

condition statements in pandas

I have a dataframe that has the following columns:
Date1
Date2
Duration (in days)
Where Date2 = Date1+duration.
I want to add a third date (date3) where date3 = date2+x,
where:
Date3 = date2+15 if duration <30days
Date3 = date2+20 if durations is from >=30days to <=180days
Date3 = date2+30 if duration >180days.
My code is:
conditions =[
(df['duration'] <30),
(df['duration'] >= 30) & df['duration'] <=180),
(df['duration'] >180)]
choices = [15,20,30]
df['date3'] = np.select(conditions,df['date2']+pd.to_timedelta(np.select(conditions, choices, default='null'),unit='d'))
If date2 = 2019-09-21, and duration is <30,
then date3 is outputted as 2019-09-21 00:00:00.00000015
so it’s considering the 15 as nanoseconds and not as days.
Any thoughts on how to make it understand that the 15 is days not nanoseconds?
I have the correct syntax for the to_timedelta statement, but not sure why its taking the delta as nanoseconds and not days.
Any help would be greatly appreciated.
Cheers,
-Big_ears
OK...so I solved it...
In the choices, instead of
choices[15,20,30]
I had to write:
choices[pd.to_timedelta(15,units='days'),pd.to_timedelta(20,units='days'),pd.to_timedelta(30,units='days')]
-big_ears
Did try your answer and wasnt successful. Maybe missed out something. This could work as well. Please Try;
Generate Data
df = pd.DataFrame({
'Date2': ['2019-01-20', '2019-01-20', '2019-01-20', '2019-01-20'],
'duration': [30, 90, 270, 15],
'Date3': ['', '', '', '']
})
df
df['Date2']= pd.to_datetime(df['Date2'])
df['Date3']= pd.to_datetime(df['Date3'])
Conditions
b=df['duration'].between(30,180)
a=df['duration']<30
c=df['duration']>180
Apply conditions and Compute Data3
df['Date3'] = np.where(a, df['Date2'] + pd.to_timedelta(15, unit='d'),df['Date3'])
df['Date3'] = np.where(b, df['Date2'] + pd.to_timedelta(20, unit='d'),df['Date3'])
df['Date3'] = np.where(c, df['Date2'] + pd.to_timedelta(30, unit='d'),df['Date3'])
df

How to extract specific set of date from a date column of an CSV file using Pandas?

I want to access some specific values from the date column from my CSV file and save to another.
here 'f' is the data frame of my csv file, "now" is the current date, "f['Date']"is the column which has to be manupilated,
LOGIC:
if current day is monday then im subtracting 2 days from the current date and then storing it in "day" and accessing the dates in f['Date'] column which are equivalent to the "day" date.
else we re subtracting only 1 day and doing the same.
now = date.today()
curr_day= now.strftime("%A")
now = now.strftime("%Y-%m-%d")
f['Date'] = pd.to_datetime(f['Date'])
# f['Date'] = f['Date'].apply( lambda x : x.strftime("%Y-%m-%d"))
f['Date'] = f['Date'].astype(str)
if curr_day == 'Monday':
day = datetime.datetime.strptime(now,"%Y-%m-%d").date() - timedelta(days=2)
day= day.strftime("%Y-%m-%d")
f['Date']=f.loc[f['Date']==day]
else:
day = datetime.datetime.strptime(now,"%Y-%m-%d").date() - timedelta(days=1)
day= day.strftime("%Y-%m-%d")
f['Date']=f.loc[f['Date']==day]
I have a date lets say: DATE1
and I need to access only those values in the date column which are equivalent to the DATE1 and the save to the new CSV file.
Date
01-Apr-19
02-Apr-19
03-Apr-19
14-Apr-19
18-Apr-19
14-Apr-19
14-Apr-19
14-Apr-19
01-Apr-19
10-Apr-19
01-Apr-19
01-Apr-19
Assume DATE1=14-04-2019
Then the updated CSV will look like
Date
14-Apr-19
14-Apr-19
14-Apr-19
14-Apr-19
I am assuming the date format you have given and adding my response. I am attaching the code for your solution!
from datetime import datetime, timedelta
import pandas as pd
data['date'] = pd.to_datetime(data['Date'],format='%d-%b-%y')
data['date'] = data['date'].apply(lambda x: x.date())
now = datetime.now()
day = now.strftime("%A")
if day=='Monday':
days_to_subtract = 2
date_filter = datetime.today() - timedelta(days=days_to_subtract)
new_data = data.loc[data['date']==(date_filter).date()]
new_data.drop('date',1,inplace = True)
new_data.reset_index(drop=True,inplace = True)
else:
days_to_subtract = 1
date_filter = datetime.today() - timedelta(days=days_to_subtract)
new_data = data.loc[data['date']==(date_filter).date()]
new_data.drop('date',1,inplace = True)
new_data.reset_index(drop=True,inplace = True)

How can I determine if a date is between two dates in Groovy?

How can I check if a date is between two other dates in Groovy? Is there any function like BETWEEN in MySQL?
There isn't any magic function but you can easily write a function to do that
Date date1 = new Date()
Date date2 = new Date().plus(2)
Date toCheck1 = new Date().plus(3)
Date toCheck2 = new Date().plus(1)
def dateBetween(Date date1, Date date2, Date toCheck){
return toCheck.after(date1) && toCheck.before(date2)
}
dateBetween(date1, date2, toCheck1) // returns false
dateBetween(date1, date2, toCheck2) // returns true
The main logic is to convert your date into the format of YYYYMMDD, then you can check if date1 <=date3 <=date2, then you can know if date 3 is between date2 and date1
Below is the code for groovy which can run in soapui. e.g. today is 20171225 an after 5 days its 20171230 . So now 20171227
def date1 = new Date().format("YYYYMMdd")
def date2 = (new Date()+5).format("YYYYMMdd")
def date3 = (new Date()+3).format("YYYYMMdd")
log.info "date1 is " + date1 + " date2 is " + date2 + " date3 is " + date3
if(date2<=date1 && date3>=date1)
{
log.info "date3 is between date1 and date2"
}
else
{
log.info "Date3 is not between date1 and date2"
}

DateFormat system.currenttimemillis()

As the date is in Milli second format, How do i convert it to have a DD/MM/YY format??
Long Ldate = System.currentTimeMillis();
String date = Ldate.toString();
Please use this code. This will help you.
long time = System.currentTimeMillis();
SimpleDateFormat dayTime = new SimpleDateFormat("dd/MM/yy");
String str = dayTime.format(new Date(time));

Resources