Convert date string to timestamp, groovy - groovy

I have a date string as follows:
201805041235040000000
Which I would like to convert to timestamp with zone in Groovy.
Tried this:
def timestamp = Date.parse("yyyyMMddHHmmss", timstamp).format("yyyy-MM-dd'T'HH:mm:ssZ");
But failed, got error:
No signature of method: static java.util.Date.parse() is applicable for argument types.
Let me know where am I going wrong.

Try this:
String t2,st = "16/08/2007 09:04:34"
SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss")
Date date = sdf.parse(st)
Timestamp timestamp = new Timestamp(date.getTime())
t2 = timestamp.toString()
Hope it helps....

This works...
String input = '201805041235040000000'
String timestamp = Date.parse('yyyyMMddHHmmss', input).format("yyyy-MM-dd'T'HH:mm:ssZ")

It is a bit unclear what you are looking for. If you just need a time stamp from parsing your date string, you can use the groovy extension Date.toTimestamp():
def ts = Date.parse("yyyyMMddHHmmssSSS", "201805041235040000000".take(17)).toTimestamp()
where the take(17) is there to discard any trailing zeros not included in the date pattern yyyyMMddHHmmssSSS. I made the assumption that three of the tailing zeros were milliseconds. If that's not the case:
def ts = Date.parse("yyyyMMddHHmmss", "201805041235040000000".take(14)).toTimestamp()
what is unclear is what you mean when you say "with zone". So assuming you just want to include the current time zone information and generate a String, I don't see a reason why you should convert from date to timestamp in the first place (Timestamp after all is a Date as it inherits from Date). If you just need the timezone spelled out you can do:
def withZone = Date.parse("yyyyMMddHHmmss", "201805041235040000000".take(14)).format("yyyy-MM-dd'T'HH:mm:ssZ")
println withZone
which on my machine where I'm sitting in Sweden prints out:
~> groovy withTimeZone.groovy
2018-05-04T12:35:04+0200

timestamp must be string. Try this:
Date.parse("yyyyMMddHHmmss", timstamp?.toString()[0..13])
.format("yyyy-MM-dd'T'HH:mm:ssZ")

Related

Convert number to datetime format

How do I Convert "1561994754" number to "2019-07-01T15:25:54.000000"
I have used :
import datetime
datetime.datetime.fromtimestamp(x['date'] / 1000.0).strftime('%Y-%m-%d %H:%M:%S.%f')
But I am getting 1970-01-18 19:53:14.754000, can you please guide me to correct function?
Thanks,
Aditya
Removing the / 1000 gives me '2019-07-01 08:25:54.000000', It seems like there was a unit mismatch in your expression. To exactly match the format you're asking for, datetime.datetime.fromtimestamp(x['date'], tz=datetime.timezone.utc).strftime('%Y-%m-%dT%H:%M:%S.%f') produces '2019-07-01T15:25:54.000000 (leaving the timezone argument blank defaults to using local time, but the human-readable date in your question uses UTC)
You can try like this!
String myString = String.valueOf(1561994754);
DateFormat format = new SimpleDateFormat("yyyy-MM-ddTHH:mm:ssZ");
Date date = format.parse(myString);

How can i format date in groovy script

Hi I have a date format that i am getting from my Jira Sprint Environment 2019-03-29T06:56:00.000-04:00
I am using groovy Script.
I have tried to use multiple format to make similar format like the above .
But Unable to do it.
Here are the below solution i have tried.
1 --
`def sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
sdf.setTimeZone(TimeZone.getTimeZone("GMT"))
log.debug("Printing Current time stamp date : "+sdf)
solution 1 is printing text only.
2 --
def now = new Date()
println now.format("yyyy-MM-dd'T'HH:mm:ss'Z'",TimeZone.getTimeZone('UTC'))
this one is printing
Printing Current time stamp date : Thu Sep 26 08:00:35 EDT 2019"
Can anyone help me on this?
So, the goal is to have date in format
2019-03-29T06:56:00.000-04:00
the following code does the formatting with timezone GMT-4
def now=new Date().format("yyyy-MM-dd'T'HH:mm:ss.SSSXXX",TimeZone.getTimeZone('GMT-4'))
println now
prints
2019-09-26T16:33:18.462-04:00
note that the variable now will contain String with formatted date
Check for all available date & time patterns:
https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html
Given that you’ve got a Java 8 or newer underneath, all you need is
OffsetDateTime.now(ZoneId.systemDefault()).toString()
In my time zone (Europe/Copenhagen) I just got
2019-09-27T21:46:53.336204+02:00
If your default time zone is America/Montreal or America/New_York, you will get the time at offset -04:00 as long as summer time (Daylight Saving Time) is in effect, then -05:00.
And you can easily parse.
OffsetDateTime.parse( "2019-09-27T21:46:53.336204+02:00" )
See this code running at IdeOne.com.
def currentDate = new Date()
def date = currentDate.format('yyyy-MM-dd')
def time = currentDate.format('HH:mm:ss.SSS')
def dateTime = date.toString() + 'T' + time.toString() + 'Z'

Check Date Format from a Python Tkinter entry widget

Using a Tkinter input box, I ask a user for a date in the format YYYYMMDD.
I would like to check if the date has been entered in the correct format , otherwise raise an error box. The following function checks for an integer but just need some help on the next step i.e the date format.
def retrieve_inputBoxes():
startdate = self.e1.get() # gets the startdate value from input box
enddate = self.e2.get() # gets the enddate value from input box
if startdate.isdigit() and enddate.isdigit():
pass
else:
tkinter.messagebox.showerror('Error Message', 'Integer Please!')
return
The easiest way would probably be to employ regex. However, YYYYMMDD is apparently an uncommon format and the regex I found was complicated. Here's an example of a regex for matching the format YYYY-MM-DD:
import re
text = input('Input a date (YYYY-MM-DD): ')
pattern = r'(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])'
match = re.search(pattern, text)
if match:
print(match.group())
else:
print('Wrong format')
This regex will work for the twentieth and twentyfirst centuries and will not care how many days are in each month, just that the maximum is 31.
Probably you've already solved this, but if anyone is facing the same issue you can also convert the data retrieved from the entry widgets to datetime format using the strptime method, and using a try statement to catch exceptions, like:
from datetime import *
def retrieve_inputBoxes():
try:
startdate = datetime.strptime(self.e1.get(), '%Y-%m-%d')
enddate = datetime.strptime(self.e2.get(), '%Y-%m-%d')
except:
print('Wrong datetime format, must be YYYY-MM-DD')
else:
print('startdate: {}, enddate: {}').format(startdate, enddate)
Note that the output string that will result will be something like YYYY-MM-DD HH:MM:SS.ssssss which you can truncate as follows the get only the date:
startdate = str(startdate)[0:10] #This truncates the string to the first 10 digits
enddate = str(enddate)[0:10]
In my opinion, this method is better than the Regex method since this method also detects if the user tries to input an invalid value like 2019-04-31, or situations in which leap years are involved (i.e. 2019-02-29 = Invalid, 2020-02-29 = Valid).

datetime.strptime with local time zone

I have in a dataframe a column time in UTC time, and I want to convert it in local time. I did this code:
from_zone = tz.tzutc()
to_zone = tz.tzlocal()
# utc = datetime.utcnow()
utc = datetime.strptime('2011-01-21 02:37:21', '%Y-%m-%d %H:%M:%S')
utc = utc.replace(tzinfo=from_zone)
# Convert time zone
central = utc.astimezone(to_zone)
Then I save it in a text file in a string.
So the string has this format:
2011-01-21 02:37:21+02:00
Then I load the text file in another program and I want to convert it in datetime format with local time zone
So I tried to use datetime.strptime() with the %Z parameter :
datetime.strptime(central,'%Y-%m-%d %H:%M:%S.%f Paris, Madrid')
Paris, Madrid is what the command datetime.tzname(central) gave me.
It is not working and I didn't find any explanations on how to use %Z.
If you have any explanations, please help me.
The datetime.strptime() function works a bit differently than this.
The first argument is the string with the time info, and the second argument is some type of formatting to it that allows the function to translate the string to a datetime object.
'.%f Paris, Madrid' is making the function think these words appear in the string, so an error will rise when the formatting and the string do not match.
The correct code would be:
datetime.strptime(central,'%Y-%m-%d %H:%M:%S%z')

How convert input String to Integer groovy

I have a String and I need to sum, but I don't know how!
How I can convert String Input like this:
01:20
to Integer for use in sum of hour and minutes?
Assuming you've got your string defined in variable:
String timeStr = '01:00'
The shortest way I can think of would look like:
timeStr[0..1].toInteger()
Just to clarify, the above line is equivalent of:
timeStr.substring(0, 2).toInteger()
Please note the difference between specifying 'to' index.
With Groovy range it's inclusive.
You can parse that into a Date using:
Date.parse( 'HH:mm', '01:00' )
If you need something to add on to a Date at a later time, you can do:
import groovy.time.*
String time = '01:00'
def duration = use( TimeCategory ) {
Date.parse( 'HH:mm', time ) - Date.parse( 'HH:mm', '00:00' )
}
Then, later on:
use( TimeCategory ) {
println new Date() + duration
}
def hours = Date.parse("HH:mm", str).getHours();

Resources