I need to compare two data in format 13.07.2017 14:03:51,469000000 using groovy
I try to do this, but get error message.
I get next data:
time1 = 13.07.2017 14:03:51,469000000
time2 = 13.07.2017 14:03:52,069000000
Then I try to compare it:
time1 = time1['TIME'] as String
time2 = time2['TIME'] as String
assert time1 > time2, 'Error'
Which type of value should I choose for date for compare it?
Whats wrong in my comparing?
You need to convert the string to Date and then compare as shown below.
In order to convert, the right date format should be used.
Here you go, comments inline:
//Define the date format as per your input
def df = "dd.MM.yyyy HH:mm:ss,S"
//Parse the date string with above date format
def dateTime1 = new Date().parse(df, "13.07.2017 14:03:51,469000000")
def dateTime2 = new Date().parse(df, "13.07.2017 14:03:52,469000000")
//Compare both date times
assert dateTime1 < dateTime2
Related
I am using pd.to_datetime(df_upload['date_field']).dt.date to get just a date from datetime object. But result of this code is indeed object type. How do I get just a date from datetime object but with data type as date not object?
It is date, check type:
out = pd.to_datetime(df_upload['date_field']).dt.date
print (out.iat[0])
print (type(out.iat[0]))
If need datetimes without times, it means times are 00:00:00:
out = pd.to_datetime(df_upload['date_field']).dt.normalize()
out = pd.to_datetime(df_upload['date_field']).dt.floor('d')
I'm still a Python beginner and the project I'm working on right now requires me to concatenate 2 float columns to datetime.
The data looks something like this
Date = [20191219, 20190812]
Time = [31547, 121652]
What's the best way to convert this to datetime format?
I tried to join both cols using dat['Date'].map(str) +''+ dat['Time'].map(str) but the values return with .0 added at the end... i.e 20191219.0, 31547.0 so datetime does not recognize this format.
Convert both columns separately to datetimes and then sum together with subtract helper dates created after converting times to datetimes:
Date = [20191219.0, 20190812]
Time = [31547, 121652.0]
dat = pd.DataFrame({'Date':Date,'Time':Time})
d = pd.to_datetime(dat['Date'], format='%Y%m%d')
t = pd.to_datetime(dat['Time'], format='%H%M%S')
dat['date'] = d + (t - t.dt.floor('d'))
print (dat)
Date Time date
0 20191219.0 31547.0 2019-12-19 03:15:47
1 20190812.0 121652.0 2019-08-12 12:16:52
Another solution is replace possible .0 to empty strings:
s = (dat['Date'].astype(str).str.replace('\.0', '') + ' ' +
dat['Time'].astype(str).str.replace('\.0', ''))
dat['date'] = pd.to_datetime(s, format='%Y%m%d %H%M%S')
I am trying to create a column that grabs just the date (ie 2004-03-18) from a column in the same dataframe. The datetime expression starts with the date (year-month-day), the letter 'T' and then the time expression. For example, "2004-03-18T07:00:00", and I am just wanting "2004-03-18" portion of the datetime.
dt = datetime.now()
UAT['Date'] = pd.to_datetime(UAT['Date']).dt.date
UAT['Date'] = pd.to_datetime(UAT['Date'], format='%Y-%m-%d')
The above code gets the following error: 'tuple' object has no attribute 'lower'
What am I doing wrong?
You might need to convert the column type to 'datetime64[ns] with astype() function, then you can retrieve just the date part of the datetimes string using date() function
UAT['Date'] = UAT['Date'].astype('datetime64[ns]')
UAT['Date'] = pd.to_datetime(UAT['Date']).dt.date
UAT['Date'] = pd.to_datetime(UAT['Date'], format='%Y-%m-%d')
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).
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")