get current date and time in groovy? - groovy

What is the code to get the current date and time in groovy? I've looked around and can't find an easy way to do this. Essentially I'm looking for linux equivalent of date
I have :
import java.text.SimpleDateFormat
def call(){
def date = new Date()
sdf = new SimpleDateFormat("MM/dd/yyyy")
return sdf.format(date)
}
but I need to print time as well.

Date has the time as well, just add HH:mm:ss to the date format:
import java.text.SimpleDateFormat
def date = new Date()
def sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss")
println sdf.format(date)
In case you are using JRE 8+ you can use LocalDateTime:
import java.time.LocalDateTime
def dt = LocalDateTime.now()
println dt

Date has the time part, so we only need to extract it from Date
I personally prefer the default format parameter of the Date when date and time needs to be separated instead of using the extra SimpleDateFormat
Date date = new Date()
String datePart = date.format("dd/MM/yyyy")
String timePart = date.format("HH:mm:ss")
println "datePart : " + datePart + "\ttimePart : " + timePart

A oneliner to print timestamp of your local timezone:
String.format('%tF %<tH:%<tM', java.time.LocalDateTime.now())
Output for example: 2021-12-05 13:20

Answering your question: new Date().format("MM/dd/yyyy HH:mm:ss")

#!groovy
import java.text.SimpleDateFormat
pipeline {
agent any
stages {
stage('Hello') {
steps {
script{
def date = new Date()
sdf = new SimpleDateFormat("MM/dd/yyyy")
println(sdf.format(date))
}
}
}
}
}

Related

How can I remove time from datetime string in dart

I have a Date time string 2021-12-12T11:11:00. I want to remove the substring T11:11:00, so that I am left with 2021-12-12.
Does anyone have any ideas? Please help me.
import 'package:intl/intl.dart'; //note --->>> import package
DateTime parsedDateTime = DateTime.parse('2021-12-12T11:11:00');
String formatDate = DateFormat("yyyy-MM-dd").format(parsedDateTime);
OUTPUT ->
2021-12-12
String _date_and_time = "2021-12-12T11:11:00";
String date = _date_and_time.split("T")[0];
print("Date is : ${date}");

How to calculate parts of a timestamp

I have a problem with my code. I have to datetime values as a string. I want to calculate the
time passed between them. I can archive this with the following code:
from datetime import datetime
fmt = '%Y-%m-%d %H:%M:%S'
tstamp1 = datetime.strptime('2021-02-20 12:25:08', fmt)
tstamp2 = datetime.strptime('2021-02-20 11:19:17', fmt)
td = tstamp1 - tstamp2
The result I get is 1:05:51.
Now I have another value as string: 00:58:08
Here I also want to know how many time passed between them:
1:05:51 - 00:58:08.
I need the result formated like this: 00:07:43
I really dont know how to do this. Can somebody help me?
This should help your requirement.
from datetime import datetime
fmt = '%Y-%m-%d %H:%M:%S'
tstamp1 = datetime.strptime('2021-02-20 12:25:08', fmt)
tstamp2 = datetime.strptime('2021-02-20 11:19:17', fmt)
td = tstamp1 - tstamp2
tr = '00:58:08'
tr = datetime.strptime(str(tr), '%H:%M:%S')
td = datetime.strptime(str(td), '%H:%M:%S')
ans = td - tr
print(ans)

Time cannot be set in the past condition Python

What I need to do.
I need this program to not allow a user to input a date that's in the past. when I try it as it currently is i get the following error message. TypeError: '<' not supported between instances of 'datetime.datetime' and 'str'.
from datetime import datetime
from datetime import date
def addNewItems():
end = 4
while end == 4:
ToDoList = [ ]
Name = input("Enter the name of your task")
dateIn = input("Enter the task completion date. yyyy/mm/dd HH:MM:SS")
date = datetime.strptime(dateIn, "%Y/%m/%d %H:%M:%S")
now = datetime.now()
now_ = now.strftime("%d/%m/%Y %H:%M:%S")
if date < now_:
print("Time entered is in the past! Select options again")
continue
if Name in ToDoList:
print("Task already exists! Select options again")
continue
if date < now_ and Name not in ToDoList:
ToDoList.append(Name, date)
print("Task Added Sucessfully")
break
You actually need two datetime objects to use the < comparison directly.
You just need to compare date with now, intead of date with now_ in order to do what you want.
And just an advice. You're importing date from datetime library, so you should avoid creating variables with the same name if you intend calling the original date somewhere else in your code

Groovy : datetime delta and JsonOutput.toJson

I'm trying to return some data from the database. When I call the method JsonOutput.toJson() with the provided data, it automatically changes the delta of my datatime.
This is my code :
def result = groovy.json.JsonOutput.toJson(data)
println(data)
println(result)
response.setContentType("application/json");
The first prints the following:
[[ DateStart:2019-01-14 09:34:51.0, DateEnd:2019-01-14 10:27:22.68]]
And the second after the json formatting show another date (hours - 1) :
[{"DateStart":"2019-01-14T08:34:51+0000","DateEnd":"2019-01-14T09:27:22+0000"}]
Any tips to format to JSON without changing any date/delta?
Based on the data.toString() output format:
[[ DateStart:2019-01-14 09:34:51.0, DateEnd:2019-01-14 10:27:22.68]]
it looks like you are dealing with JSON serialization of thejava.sql.Timestamp type. If you want to prevent the default timestamp serializer from being used, you will have to format timestamps manually before JSON serialization happens.
Consider the following example:
import groovy.json.JsonOutput
import java.sql.Timestamp
def format = "yyyy-MM-dd'T'hh:mm:ss.S"
def date = new Date().parse(format, "2019-01-14T09:34:51.0")
def dateStart = new Timestamp(date.time)
def dateEnd = new Timestamp((date + 20).time)
def data = [[DateStart: dateStart, DateEnd: dateEnd]]
println "Raw data:"
println data
println "\nJSON without formatting:"
println JsonOutput.toJson(data)
data = data.collect { el -> el.collectEntries { k,v ->
def value = v instanceof Timestamp ? v.format(format) : v
return [(k): value]
}}
println "\nJSON after formatting:"
println JsonOutput.toJson(data)
The output:
Raw data:
[[DateStart:2019-01-14 09:34:51.0, DateEnd:2019-02-03 09:34:51.0]]
JSON without formatting:
[{"DateStart":"2019-01-14T08:34:51+0000","DateEnd":"2019-02-03T08:34:51+0000"}]
JSON after formatting:
[{"DateStart":"2019-01-14T09:34:51.0","DateEnd":"2019-02-03T09:34:51.0"}]
The most important part (formatting timestamp value to its string representation) happens in the following part:
data = data.collect { el -> el.collectEntries { k,v ->
def value = v instanceof Timestamp ? v.format(format) : v
return [(k): value]
}}
It assumes that your list of maps may contain other key-value pairs which don't hold the timestamp value. If we deal with a timestamp, we format it using yyyy-MM-dd'T'hh:mm:ss.S format, and we return a not-modified value otherwise.

date-time-string to UNIX time with milliseconds

I need to convert a date/time string to UNIX timestamp including the milliseconds. As the timetuple() does not include milli or microseconds I made a short workaround. But I was wondering, is there a better/nicer way to do this?
import datetime as dt
import time
timestamp = '2018-01-19 10:00:00.019' # example of input time string
tmp = timestamp.split('.')
millisec = tmp[-1] # extracting only milli-seconds
UX_time = time.mktime(dt.datetime.strptime(tmp[0], '%Y-%m-%d %H:%M:%S').timetuple()) + float(millisec)/1e3
print(UX_time)
1516352400.019
I realize my timezone is off by one hour, so you might be getting
print(UX_time)
1516356000.019
you can try this:
timestamp = '2018-01-19 10:00:00.019'
tmp=np.datetime64(timestamp)
print(tmp.view('<i8')/1e3)
output:
1516352400.019
Also possible with your current code:
import datetime as dt
import time
timestamp = '2018-01-19 10:00:00.019' # example of input time string
ts = dt.datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S.%f')
UX_time = time.mktime(ts.timetuple()) + ts.microsecond/1e6
print "%.3f" %UX_time

Resources