So far I have used the following code to get the date of yesterday:
def today = new Date()
def yesterday = today - 1
yesterday.format( '"yyyy-MM-dd 23:59:59"' )
Result today: "2021-02-25 23:59:59"
Now I want to get the exact same result but instead of " I only want to have a single quotation mark looking like this:
'2021-02-25 23:59:59'
Therefore, I tried mutliple ways to modify the code above for example:
def today = new Date()
def yesterday = today - 1
yesterday.format( '''yyyy-MM-dd 23:59:59''' )
However, so far all my trials lead to this result: 2021-02-25 23:59:59
As you can see in this result there is no quotation mark at all.
What do I need to change to the result including the single quotation mark?
This will give you the output you want:
yesterday.format( "''yyyy-MM-dd 23:59:59''" )
Related
im working on small project and i need to display date from api , api uses millisecounds and i cant really find a way to get date without time.
So far i didnt find anything usefull on internet.
Code i was using for this is:
ts= millisecounds im using
date = datetime.datetime.fromtimestamp(ts / 1000, tz=datetime.timezone.utc)
print(date)
But it prints something like 2010-10-10 10:10:10.100000+00:00
only thing i want from this is first part (2010-10-10)
how can i get date?
1. Naive Solution:
If you just want the date, you can try using the split method:
Code:
year_month_day = date.split(" ")[0]
print(year_month_day)
Output:
2010-10-10
2. Using strftime():
# using strftime
ts = 1588234567899 # Unix time in milliseconds
ts /= 1000 # Convert millisecondsto seconds
datetime_object = datetime.utcfromtimestamp(ts) # Create datetime object
date = datetime_object.strftime('%Y-%m-%d') # Strip just the date part out
print(date)
Output:
2020-04-30
My first python project that didn't print 'Hello World' - so be gentle. Tried answers from similar questions but they don't seem to work.
I'm working with an Excel file, parsing as pandas dataframe.
I have a calculated column that calculates the number of days to later be added to a date. The number of days to add column is done as below, with 'choices' being a list of integers. This seems to work fine.
choices = [0,0,925,778,567,608, 638,730]
df['Days_to_add'] = np.select(conditions, choices, default=0)
I now want to add this to an existing date column, to return a new column with the new date. So far i've tried this but Jupyter says its depreciated and will return a TypeError in a future version:
df["Estimated Start"] = pd.to_timedelta(df["Date1"]) + df['Days_to_add']
Also tried this:
df['Estimated_Start'] = df.Max_Dec_Date + pd.DateOffset(df['Days_to_add'])
And something else that told me to use timedelta index, and something else that pointed to timedelta range. I think the problem is something to do with trying to add an integer to a series?
No success with any of it. Help?
Date is not TimeDelta, but DateTime,
so the addition should go like this:
df["Estimated Start"] = pd.to_datetime(df["Date1"]) + pd.to_timedelta(df['Days_to_add'], unit='D')
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'
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 am trying to do a simple add a day to my substring text that i've parsed into a date but it is not displaying correctly.
Below is the code:
def dateTimeDate = Date.parse("yyyy-mm-dd", textfromjson.substring(0,10)).format("yyyy-mm-dd")
def futureDateTimeDate = dateTimeDate + 1
When I do two logs for both defs, the original date and the future date which I want to be next day, I receive this output:
logs:
log.warn dateTimeDate
log.error futureDateTimeDate
output:
2018-02-23
2018-02-231
How can I get this to work so that it outputs: 2018-02-24 and not 2018-02-231
The answers posted already correctly point out that the date value needs to be incremented before it's formatted back into a String.
To this, I would like to add that if you're on Java 8 you can use its new Date/Time API as an alternative to java.util.Date, which can be problematic (even apart from mixing up 'm' and 'M' in format strings).
import java.time.*
def future = LocalDate.parse(textfromjson.substring(0,10)) + Period.ofDays(1)
You're parsing a String into a Date and then formatting it back into a String. Add to the Date object, not the String object.
def dateTimeDate = Date.parse("yyyy-mm-dd", textfromjson.substring(0,10))
def futureDateTimeDate = dateTimeDate + 1
log.warn dateTimeDate.format("yyyy-MM-dd")
log.error futureDateTimeDate.format("yyyy-MM-dd")
Also note that you probably want to be using MM (month in year) not mm (minute in hour).