Groovy String data to Date - groovy

How to convert String to Date ?
I tried this:
#RequestMapping("/data/{data}")
String buscar(#PathVariable String data, Model model) {
model.addAttribute 'dataBuscar', data
def newDate = data
def df1 = new SimpleDateFormat("dd/MM/yyyy 00:00:00")
data = df1.parse(newDate)
model.addAttribute 'acessos', acessoService.buscar(data)
'acesso/acesso.index'
}
but show me this message:
Unparseable date: "12-01-2014"
Why? Any idea ?

Your SimpleDateFormat pattern does not match the string you're trying to parse.
If you need to parse a string like "12-01-2014", you need:
new SimpleDateFormat("dd-MM-yyyy");
Tested Groovy script:
import java.text.SimpleDateFormat
def format = new SimpleDateFormat("dd-MM-yyyy")
def date = format.parse("14-01-2014")
println date // prints "Tue Jan 14 00:00:00 CST 2014"
As #tim_yates points out, Groovy provides the convenient method:
Date.parse('dd-MM-yyyy', "14-01-2014")

Related

Python convert a str date into a datetime with timezone object

In my django project i have to convert a str variable passed as a date ("2021-11-10") to a datetime with timezone object for execute an ORM filter on a DateTime field.
In my db values are stored as for example:
2021-11-11 01:18:04.200149+00
i try:
# test date
df = "2021-11-11"
df = df + " 00:00:00+00"
start_d = datetime.strptime(df, '%Y-%m-%d %H:%M:%S%Z')
but i get an error due to an error about str format and datetime representation (are different)
How can i convert a single date string into a datetimeobject with timezone stated from midnight of the date value?
So many thanks in advance
It's not the way to datetime.strptime.
Read a little bit more here
I believe it will help you.
you should implement month as str and without "-".
good luck

Pyspark change string to timestamptype

I am new to PySpark and I am trying to create a function that can be used across when inputted a column from String type to a timestampType.
This the input column string looks like: 23/04/2021 12:00:00 AM
I want this to be turned in to timestampType so I can get latest date using pyspark.
Below is the function I so far created:
def datetype_change(self, key, col):
self.log.info("datetype_change...".format(self.app_name.upper()))
self.df[key] = self.df[key].withColumn("column_name", F.unix_timestamp(F.col("column_name"), 'yyyy-MM-dd HH:mm:ss').cast(TimestampType()))
When I run it I'm getting an error:
NameError: name 'TimestampType' is not defined
How do I change this function so it can take the intended output?
Found my answer:
def datetype_change(self,key,col):
self.log.info("-datetype_change...".format(self.app_name.upper()))
self.df[key] = self.df[key].withColumn(col, F.unix_timestamp(self.df[key][col], 'dd/MM/yyyy hh:mm:ss aa').cast(TimestampType()))

Oracle: date not valid for month specified in groovy

Using RestApi i am trying to fetch response and saving the data into database using groovy and java.
I have field Allocation Date where the format i am receiving from RestApi is for example
'"2020-06-30".
So in my java IData class i have created method as IN_DATE_FORMAT for input format:
public static final DateFormat IN_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
And in groovy class i have created constructor and using this method like below:
def contents = json.Contents as ArrayList
contents.parallelStream().each { rec ->
IData data = new IData ()
def allocDate = rec["Allocation Date"]
data.allocationDate = allocDate != null ? IData .IN_DATE_FORMAT.parse(allocDate as String) : null
When i am running the code i am getting in between few error as
ORA-01839: date not valid for month specified
And i am receiving corrupt date as for example '31-Apr-20' which is normally not correct as in April month we dont have date 31. And this value is not coming from RestApi. I dont understand from where this corrupt date value is coming from. Is it because of conversion and parsing the date into String ?
Can we use something like LocalDate in my code as this looks risky of parsing date into string ? And i think because of which its trying to store incorrect date value in database which even does not exist and received from RestApi.
Below are my logs for def allocDate = rec["Allocation Date"]:
WARNING: Failed to execute: insert into XXX (
ALLOCATIONDATE
) values (
'31-Apr-20'
)
because: ORA-01839: date not valid for month specified
10:57:16.103 [Actor Thread 3] WARN XXXX - Failed to execture record due to:ORA-01839: date not valid for month specified
Allocation Date:- 2020-06-30
Allocation Date:- 2020-06-25
Allocation Date:- 2020-07-30
Allocation Date:- 2020-05-30
Allocation Date:- 2020-06-25
....
Below is my Insert into DB method:
private boolean insertIntoDb(Map<String, List<IData>> ricMap) {
Sql conn = sql(ORACLE)
conn.withTransaction {
ricMap.entrySet().parallelStream().forEach { entry ->
entry.value.parallelStream().forEach { val ->
String values = """
${nullStr(val.allocationDate != null ? DbConnCfg.ORACLE_DATE_FORMAT.format(val.allocationDate) : null)}
"""
}
}
}
In DbConnCfg class i have defined ORACLE_DATE_FORMAT method as below:
public static final DateFormat ORACLE_DATE_FORMAT = new SimpleDateFormat("dd-MMM-yy");
You can parse a given date by using Date.parse(format, date). In your case, 31 April is parsed as May 1st. I don't know if this will solve your problem.
dt1 = '30-Apr-20'
dt2 = '31-Apr-20'
def format(dt) {
def newDt = new Date().parse("dd-MMM-yy", dt) //reverse-engineers the date, keeps it a Date object
return newDt.format("yyyy-MM-dd") //apply the format you wish
}
assert format(dt1) == '2020-04-30'
assert format(dt2) == '2020-05-01'

convert scientific notation to datetime

How can I convert date from seconds to date format.
I have a table containing information about lat, long and time.
table
f_table['dt'] = pd.to_datetime(f_table['dt'])
f_table["dt"]
it results like this:
output
but the output is wrong actually the date is 20160628 but it converted to 1970.
My desired output:
24-April-2014
The unit needs to be nanoseconds, so you need to multiply with 1e9
f_table['dt'] = pd.to_datetime(f_table['dt'] * 1e9)
This should work.
#Split your string to extract timestamp, I am assuming a single space between each float
op = "28.359062 69.693673 5.204486e+08"
ts = float(op.split()[2])
from datetime import datetime
#Timestamp to datetime object
dt = datetime.fromtimestamp(ts)
#Datetime object to string
dt_str = dt.strftime('%m-%B-%Y')
print(dt_str)
#06-June-1986

date column which is a text type in Cassandra.so I need a UDF to convert that text to timestamp so I can query on that column

I have writeen code like belo but getting error as below:-
InvalidRequest:  Error from server:  code=2200 [Invalid query]  message="Java source compilation failed: Line 1: java.util.String cannot be resolved to a type  Line 1: Syntax error on token "Date", # expected  Line 4: SimpleDateFormat cannot be resolved to a type
CREATE FUNCTION saumya.text2dt ( input text )
RETURNS NULL ON NULL INPUT
RETURNS timestamp
LANGUAGE java
AS $$
java.text.ParseException
java.text.SimpleDateFormat
java.util.Date
String ms = input;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date date = sdf.parse(ms);
return sdf.format(date);
$$
Create UDF syntax:
CREATE FUNCTION text2dt ( input text )
RETURNS NULL ON NULL INPUT
RETURNS timestamp
LANGUAGE java
AS '
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
try{
java.util.Date date = sdf.parse(input);
return date;
}catch(Exception e){
return null;
}
';

Resources