I have some created and updated datetime coming in dynamically from JIRA API for an automation process for getting JIRA tickets on a monthly basis using a python script to load into an excel sheet.
Some of the sample dates are as follows:
What I would like to present this is in a format like %d-%b-%Y (ex: 09-Feb-2017)
I have tried using python datetime.strptime
and strftime
.
Sample code as below:
from datetime import datetime
datetimeObj = datetime.strptime('2017-02-09T09:43:04.216+1000', '%Y-%m-%dT%H:%M:%S.%f+1000')
print(datetimeObj.strftime('%d-%b-%Y'))
This gives me the result as expected but now I have hardcoded the values like date I wanted and in the datetime format I have added +1000
but since its dynamically changing datetime I get stuck when the datetime ends with values such as +1100
.
I believe the last part is something to do with the daylight savings but I am not able find the right format for this in this case.
Is there anyway to convert the datetime format for this for the last +1000
and +1100
part instead of hardcoding like '%Y-%m-%dT%H:%M:%S.%f+1000'
like this?
Just found an answer to this. Hope this may help others too if someone else is stuck like me.
from datetime import datetime
datetimeObj = datetime.strptime('2017-02-09T09:43:04.216+1000', '%Y-%m-%dT%H:%M:%S.%f%z')
print(datetimeObj.strftime('%d-%b-%Y'))
Using %z
will solve the problem.
%z
is UTC offset in python strftime()
and strptime()
in the form +HHMM or -HHMM (empty string if the the object is naive).
This helps when there are values such as (empty), +0000, -0400, +1030
at the end of time format.