[英]How to convert a datetime format like 2017-02-09T09:43:04.216+1000 to 09-Feb-2017 using python strptime and strftime?
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. 我有一些动态来自JIRA API的创建和更新日期时间,用于自动化过程,每月使用python脚本加载到Excel工作表中获取JIRA票证。
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) 我想提出的是%d-%b-%Y的格式(例如:2017年2月9日)
I have tried using python datetime.strptime
and strftime
. 我尝试过使用python datetime.strptime
和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
. 这给了我预期的结果,但现在我已经硬编码了我想要的日期值,并且在日期时间格式中我添加了+1000
但是由于动态变化的日期时间,当日期时间以+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? 无论如何转换为最后+1000
和+1100
部分的日期时间格式而不是像'%Y-%m-%dT%H:%M:%S.%f+1000'
这样的硬编码?
seems you already figured out a solution but if this is always the format.. 似乎你已经找到了解决方案,但如果这始终是格式..
you can do: 你可以做:
date = '2017-02-09T09:33:33.508+1100'
d = re.search('[0-9]+-[0-9]+-[0-9]+',date).group()
d = re.search('([0-9]+-)+[0-9]+',date).group()
d = date.split('T')[0]
d = date[0:10]
or some variant of this...then: 或者这个的一些变体...然后:
print(datetime.strptime(d,'%Y-%m-%d').strftime('%d-%b-%Y'))
or 要么
print(datetime.strptime(''.join(re.findall('\d+',date)[0:3]),'%Y%m%d').strftime('%d-%b-%Y'))
:) :)
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
将解决问题。
%z
is UTC offset in python strftime()
and strptime()
in the form +HHMM or -HHMM (empty string if the the object is naive). %z
是python strftime()
和strptime()
中的UTC偏移量,格式为+ HHMM或-HHMM(如果对象是天真的,则为空字符串)。
This helps when there are values such as (empty), +0000, -0400, +1030
at the end of time format. 当在时间格式结束时存在诸如(empty), +0000, -0400, +1030
类的值时,这会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.