如何在Python中格式化从表中获取的Date?

问题描述 投票:0回答:2

这是我的代码,我把数据写入一个文件。我如何将我的dob变量转换成不同的日期格式。Dob 目前在文件中的数据为 2020 -04 -30 00:00:00 但我希望它显示为4302020。有什么建议吗?

    with open(r"C:\inetpub\ftproot\mhv\mhv_exportdetail.txt",'w') as f:
    for companyrow in company_rows:
        # Joining the ints,and strings in the tuple to convert to a string
        newRow = '\t'.join(map(str,companyrow))
        #print(newRow)

        dob  =(companyrow[12])
python python-3.x
2个回答
0
投票

像这样的东西应该对你有用。

from datetime import datetime

previous_datetime = "2020-04-30 00:00:00"
new_datetime = datetime.strptime(previous_datetime, '%Y-%m-%d %H:%M:%S').strftime('%m/%d/%Y')
print(new_datetime)

这将输出。

04/30/2020

我建议你学习一下 strftime()和strptime()格式码。因为它们可以证明是非常有用的。


0
投票
from datetime import datetime

oldformat = '2020-04-30 00:00:00'
dob = datetime.strptime(oldformat,'%Y-%m-%d %H:%M:%S').strftime('%m/%d/%Y')
print (dob)

印品。

04/30/2020
© www.soinside.com 2019 - 2024. All rights reserved.