Python 3 working with date objects - python-3.x

I have a variable storing a date object
CreateDate = keyData["CreateDate"] that is storing a value like "2017-01-11 19:40:26+00:00" (depends on the date) and I am wanting to use that date in addition with today's date to find out how many days it has been between the two. So for example if the create date was 2017-07-10 and today's date is 2017-07-18 then I would like the output to be the amount of days passed. I have tried working with the datetime module like datetime.combine(date.today(), createdate) - datetime.combine(date.today(), todaysDate) but still run into issues and think there might be a simpler way to get the total days passed between the two.
todaysDate = strftime("%Y-%m-%d %H:%M:%S", gmtime())
todaysDate = str(todaysDate)
todaysDate = todaysDate[0:10]
todaysDate = datetime.strptime(todaysDate, "%Y-%m-%d")
CreateDate = datetime.strptime(CreateDate, "%Y-%m-%d")
totalDays = abs((CreateDate - todaysDate).days)
print (totalDays)
`

Related

converting utc to est time in python

I have two dates, start date and end date, where both needs to used in google tag manager in EST timezone using python.
Currently when I fetch the dates from jira using api, I am getting in the UTC format for start date, but for end date, getting only the date value, that too in class str type.
This is what I got from jira
start date: 2021-09-20T07:16:08.000+0000
end date: 2021-09-21
Now I need to convert these and create a tag using python gtm api, where the start and end date should be in EST timezone.
Time in start date should be 00:00:00 and in end date, it should be 23:59:59 (both the time in EST).
Anyone please help me on this?
If im underderstanding correctly, it are both strings that you are getting back like this?
startdate = "start date: 2021-09-20T07:16:08.000+0000"
enddate = "end date: 2021-09-21"
Then first what you want to do, is split on the spaces and select the last item
justStartDatetimeString = startdate.split(" ")[-1]
justEndDatetimeString = enddate.split(" ")[-1]
If you just get the datetime as string like this, ignore part above:
"2021-09-20T07:16:08.000+0000"
Now just parse it towards a datetime by using the dateutil.parser
from datetime import datetime, time, timezone
import dateutil.parser
startdateDateTime = dateutil.parser.isoparse(justStartDatetimeString)
startdateDateTime = startdateDateTime.replace(tzinfo=timezone.utc).astimezone(tz=dateutil.tz.gettz('US/Eastern'))
startdateDateTime = startdateDateTime.replace(hour=0, minute=0, second=0)
For the enddate string
enddateDateTime = dateutil.parser.isoparse(justEndDatetimeString)
enddateDateTime = enddateDateTime.replace(tzinfo=dateutil.tz.gettz('US/Eastern'))astimezone(tz=dateutil.tz.gettz('US/Eastern'))
enddateDateTime = enddateDateTime.replace(hour=23, minute=59, second=59)

How to get 1st calendar day of the current and next month based on a current date variable

I have a date variable calls today_date as below. I need to get the 1st calendar day of the current and next month.
In my case, today_date is 4/17/2021, I need to create two more variables calls first_day_current which should be 4/1/2021, and first_day_next which should be 5/1/2021.
Any suggestions are greatly appreciated
import datetime as dt
today_date
'2021-04-17'
Getting just the first date of a month is quite simple - since it equals 1 all the time. You can even do this without needing the datetime module to simplify calculations for you, if today_date is always a string "Year-Month-Day" (or any consistent format - parse it accordingly)
today_date = '2021-04-17'
y, m, d = today_date.split('-')
first_day_current = f"{y}-{m}-01"
y, m = int(y), int(m)
first_day_next = f"{y+(m==12)}-{m%12+1}-01"
If you want to use datetime.date(), then you'll anyway have to convert the string to (year, month, date) ints to give as arguments (or do today_date = datetime.date.today().
Then .replace(day=1) to get first_day_current.
datetime.timedelta can't add months (only upto weeks), so you'll need to use other libraries for this. But it's more imports and calculations to do the same thing in effect.
I found out pd.offsets could accomplish this task as below -
import datetime as dt
import pandas as pd
today_date #'2021-04-17' this is a variable that is being created in the program
first_day_current = today_date.replace(day=1) # this will be 2021-04-01
next_month = first_day_current + pd.offsets.MonthBegin(n=1)
first_day_next = next_month.strftime('%Y-%m-%d') # this will be 2021-05-01

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'

Find date upon which defined age in seconds is reached

I am attempting to write a program that
takes a certain number of seconds (say 1000000000), then
takes a given date (for example one's birthday) and
then determines when (at which given date) this age in number of seconds has been reached.
Certainly, the program should recognize if that age in number of seconds is in the past.
But even before building a check for this, the code runs into problems.
After receiving error message I tried changing parameter name from month to umonth in the input stage. That brought no difference.
from datetime import datetime
seconds = int(input("seconds: "))
year = int(input("year: "))
month = int(input("month: "))
day = int(input("day: "))
#Calculate time in seconds between now and the day of birth
date = (datetime(year=year, month=month, day=day) - datetime(seconds)).total_seconds()
print("You will be {} seconds old on {} old.".format(seconds, date))
I am still dabbling with the datetime library.
I received a TypeError from python3.
"TypeError: Required argument 'month' (pos 2) not found"
Edit:
Following suggestions in the comments, I modified the code for using a new method, to convert a date into seconds.
from datetime import datetime
#seconds = int(input("seconds: "))
seconds = 1000000000
#year = int(input("year: "))
#month = int(input("month: "))
#day = int(input("day: "))
year = 1987
month = 9
day = 11
date = datetime.datetime(year,month,day)
#Calculate time in seconds between now and the day of birth
(date.total_seconds(datetime(year=year, month=month, day=day)) - seconds)
print("You will be {} seconds old on {} old.".format(seconds, date))
That yields an AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
I am aware I dont know exactly how to use datetime library.
Working through the docs to understand.
But still, those things seem trivial to achieve.
Perhaps someone can explain.
The goal is, as before, to take a number of seconds and a date of birth.
And to see when, from the date of birth on, the number of seconds will be reached.
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
You are receiving the above error because you already used import datetime. No need of writing datetime.datetime. You can directly use datetime(year, month, day).

How to compare date in Groovy?

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

Resources