converting utc to est time in python - python-3.x

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)

Related

Using timezone with openpyxl

I need to add a date in an excel file.
I use timezones on these dates. It works very well with django rest framework. (My GET requests return the date with this format: 2022-07-23T13:19:59+02:00) Same in Django admin, the Europe/Paris timezone is well taken into account (+02:00).
However, when I use openpyxl, the indicated time is 2h late (it takes the UTC timezone).
sheet.append([date_recorded.strftime("%d/%m/%Y %H:%M:%S")])
Same thing if I print this date in console. (2022-07-11 15:19:50+00:00)
How to correct this?
You can simply convert it to your desired zone like this:
from dateutil import tz
utctime = "YOUR CURRENT VALUE OF DATETIME"
from_zone = tz.gettz("UTC")
to_zone = tz.gettz("yourzone")
utctime = utctime.replace(tzinfo=from_zone)
new_time = utctime.astimezone(to_zone)
Since you are using django, you can use built-in get_current_timezone to convert datetime objects to the local timezone:
from django.utils import get_current_timezone
timezone = get_current_timezone()
date_recorded = date_recorded.astimezone(timezone)
sheet.append([date_recorded.strftime("%d/%m/%Y %H:%M:%S")])

What's a good way of converting timezone of a timestamp?

I have a string in this format: 09/20/2020 10:30 AM
That timestamp is in Eastern Timezone.
I need to obtain the UTC equivalent, but in the following ISO format: 2020-09-20T14:30:00.0000Z
I've tried a few things but there doesn't seem to be a clean/short way of converting it.
So far I've tried:
dtSept = "09/20/2020 10:00 PM"
dtSeptTZ = pytz.timezone('US/Eastern').localize(datetime.datetime.strptime(dtSept, "%m/%d/%Y %I:%M %p")).isoformat(timespec='milliseconds')
dtSeptTZ at this point is a string object.
If I have to convert its TimeZone and format it, I have to execute the following which each take a datetime object but return a string.
dtSeptTZ.astimezone(pytz.timezone('Etc/UTC'))
dtSeptTZ.strftime("%Y-%m-%dT%I:%M.%fZ")
Is there a clean/short way of getting the proper output without coverting it back and forth between string and datetime?
Many thanks.
due to the immanent deprecation of pytz, I'd suggest to use dateutil. The usage of dateutil also transforms nicely to Python 3.9's zoneinfo.
from datetime import datetime, timezone
from dateutil.tz import gettz
dtSept = "09/20/2020 10:00 PM"
# string to datetime object
dt = datetime.strptime(dtSept, "%m/%d/%Y %I:%M %p")
# set tzinfo to appropriate time zone; (!) use "localize" instead with pytz timezone class
dt = dt.replace(tzinfo=gettz('US/Eastern'))
# to UTC (could use any other tz here)
dt_utc = dt.astimezone(timezone.utc)
# to ISO format string:
print(dt_utc.isoformat())
>>> 2020-09-21T02:00:00+00:00

Convert a custom formatted date from string to a datetime object

I am trying to convert a string to a datetime format which has the following format
YYYYMMDD:HHMM
As an example:
20200712:1834 which is 2020/07/12 18:34
It is not difficult to extract the information from the string one by one and get year, month, day and the time. But I was wondering if there is a suphisticated way of doing this. For example, I tried the following:
from datetime import datetime
date_time_str = '20200712:1834'
date_time_obj = datetime.strptime(date_time_str, '%y%m%d:%H%M')
Could someone kindly let me know?

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'

How to get day from date using groovy

I want to get day (Ex Sun, Mon, Tue, ..) from date
def date = new Date()
def day = date[Calendar.DAY_OF_MONTH]
result is 18, but i want to get Mon.
And if I have 2017-10-09T00:00:00.000, I want to get day of 2017-10-09T00:00:00.000
Could you help me please?
The below code can help. It gets today's date first which is 18 Sep 2017 and then thats passed into calendar instance
Calendar instance then get the day in integer form i.e. monday=2, Then once we get the value 2 using map we say its Monday
def date = new Date()
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
def day = calendar.get(Calendar.DAY_OF_WEEK);
def map=[
1:"Sunday",
2:"Monday",
3:"Tuesday",
4:"Wednesday",
5:"Thursday",
6:"Friday",
7:"Saturday"]
log.info map[day]
Try Calendar.DAY_OF_WEEK. This returns an int which you can later map to the respective string.
Try using SimpleDateFormat, with EE format which tells days of week.
try below code :
def date = new Date()
SimpleDateFormat("EE").format(date) // EE means days of week
You can use this to output a three character representation of the name of the week day:
theDate = "2017-10-09T00:00:00.000";
def parsedDate = new Date().parse("yyyy-MM-dd'T'HH:mm:ss.SSS", theDate);
def day = new java.text.SimpleDateFormat("EEE", Locale.ENGLISH).format(parsedDate);
or for the full name use EEEE pattern.
Make sure to specify the Locale as this could differ per server configuration.

Resources