如何转换字符串,例如:
'20190501'
到一个字符串,例如:
'2019-05-01'
例如,无需先转换为日期时间:
from datetime import datetime
datetime.strptime('20190501', '%Y%m%d').strftime('%Y-%m-%d'))
上面的代码有效,但是由于我以字符串开头和结尾,因此似乎不需要在过程中使用datetime
。我可以直接转换字符串吗?
答案 0 :(得分:2)
您可以切片和格式化
>>> date = '20190501'
>>> newdate = "{}-{}-{}".format(date[:4],date[4:6],date[6:])
>>> newdate
'2019-05-01'
答案 1 :(得分:2)
如果格式始终为YYYYMMDD,则可以通过以下方式获取字词来对其进行转换:
s="YYYYMMDD"
s=s[:4]+"-"+ s[4:6]+"-"+s[6:]
答案 2 :(得分:1)
如果您知道格式是固定的,那么使用字符串切片就很简单了。
d = '20190501'
print(d[0:4] + '-' + d[4:6] + '-' + d[6:8])
答案 3 :(得分:1)
尝试一下:
before = '20190501'
print('before:', before)
after = ''.join((before[:4],'-',before[4:6],'-',before[6:]))
print('after:', after)
答案 4 :(得分:0)
您可以按如下方式使用字符串索引。
old_date ='20200505'
new_date = old_date [:4] +'-'++ old_date [4:6] +'-'++ old_date [6:8]
打印(新日期)
2020-05-05