Python日期转换脚本

时间:2019-03-15 23:12:12

标签: python date

我试图制作一个脚本,将excel的日期从mm / dd / yyyy转换为dd / m(m)?/ yyyy格式。以下是我的工作。我想问问是否有更好,更有效的方法用更少的代码行来完成同一件事?

我是新手,还在学习。抱歉,如果代码看起来很愚蠢...

text='''
09/29/2016
07/25/2016
07/25/2016
06/17/2016
06/17/2016
5/5/2016
5/5/2016
4/4/2016
4/4/2016
3/7/2016
3/7/2016
2/8/2016
2/8/2016
2/8/2016
'''
def dataConvert(x):
    text2=list(x.split('\n'))       #makes new list, splits old throug new lines
    del text2[-1]
    text3=[]
    for i in range(len(text2)):     #makes new list, splits old through /
        text3.append(list(text2[i].split('/')))
    for i in range(len(text3)):     #delets ZERO in months, which are still first
        if text3[i][0][0]=='0':
            text3[i][0]=text3[i][0][1]
    for i in range(len(text3)):     #days to front of the sublists
        text3[i].insert(0,text3[i][1])
        del text3[i][2]             #removes days from the middle
    text4=[]
    for i in range(len(text3)):     #joins finished list
        text4.append('/'.join(text3[i]))
    text5='\n'.join(text4)
    print(text5,'\n')
dataConvert(text)

1 个答案:

答案 0 :(得分:0)

方法1:字符串拆分和一些索引:

foundTeacher._id.equals(req.user.profile)

输出:

text = '''09/29/2016
07/25/2016
07/25/2016
06/17/2016
06/17/2016
5/5/2016
5/5/2016
4/4/2016
4/4/2016
3/7/2016
3/7/2016
2/8/2016
2/8/2016
2/8/2016'''

text2 = text.split('\n')

for date in text2:
    split_up_date = date.split('/') # makes a list in mm/dd/yyyy format
    new_date = "{}/{}/{}".format(split_up_date[1], split_up_date[0], split_up_date[2]) # makes a string in dd/mm/yyyy format
    print(new_date)

方法2:29/09/2016 25/07/2016 25/07/2016 17/06/2016 17/06/2016 5/5/2016 5/5/2016 4/4/2016 4/4/2016 7/3/2016 7/3/2016 8/2/2016 8/2/2016 8/2/2016 模块:

datetime

结果:

import datetime

text = '''09/29/2016
07/25/2016
07/25/2016
06/17/2016
06/17/2016
5/5/2016
5/5/2016
4/4/2016
4/4/2016
3/7/2016
3/7/2016
2/8/2016
2/8/2016
2/8/2016'''

text2 = text.split('\n')

for date in text2:
    datetime_date = datetime.datetime.strptime(date, '%m/%d/%Y')
    altered = datetime_date.strftime('%d/%m/%Y')
    print(altered)

这是一个很好的统一结构。此外,您可以使用

中提供的多种格式轻松地根据自己的喜好重新对其进行重新排列。

https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior