如何将日期格式从“2016年11月3日”更改为2016年11月3日

2024-10-02 00:30:07 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是我在2.7中尝试的python代码

def date_format_change():
    DB_date = "03-NOV-2016"
    split2 = DB_date.split('-')
    print split2[0]
    M_date = float(round(split2[0]),2)
    print M_date
    Month = {'JAN': '1', 'FEB': '2', 'MAR': '3', 'APR': '4', 'MAY': '5','JUN': '6', 'JUL': '7', 'AUG': '8', 'SEP': '9',
    'OCT': '10', 'NOV': '11', 'DEC': '12'}
    DB_Month = str(split2[1])
    print DB_Month
    M_Month = int(Month[DB_Month])
    M_year = split2(2)
    print M_year
    Changed_format = str(M_Month) +"/"+ str(M_date)+"/"+ str(M_year)
    print Changed_format

date_format_change()

但我说的是错误的:

Traceback (most recent call last):
  File "C:/Users/aannam002c/workspace/Website/Century/views.py", line 17, in <module>
03
    date_format_change()
  File "C:/Users/aannam002c/workspace/Website/Century/views.py", line 5, in date_format_change
    M_date = float(round(split2[0]),2)
TypeError: a float is required

Process finished with exit code 1

有人能帮忙吗?你知道吗


Tags: formatdbdatefloatchangeyearusersnov
3条回答

float()接受一个参数,您给出了两个参数,而且日期的float类型看起来不太好。int就可以了。另外,round接受一个数字,split2[0]是一个字符串。你知道吗

这可能就是你想要的:

def date_format_change():
    DB_date = "03-NOV-2016"
    split2 = DB_date.split('-')
    M_date = int(split2[0])
    Month = {'JAN': '1', 'FEB': '2', 'MAR': '3', 'APR': '4', 'MAY': '5','JUN': '6', 'JUL': '7', 'AUG': '8', 'SEP': '9',
    'OCT': '10', 'NOV': '11', 'DEC': '12'}
    print (M_date)
    DB_Month = split2[1]
    print (DB_Month)
    M_Month = int(Month[DB_Month])
    M_year = split2[2]
    print (M_year)
    Changed_format = str(M_Month) +"/"+ str(M_date)+"/"+ str(M_year)
    print (Changed_format)

date_format_change()

它返回:

3
NOV
2016
11/3/2016

以下是解决您问题的简单方法:

from datetime import datetime
DB_date = "03-NOV-2016"
print datetime.strptime(DB_date, '%d-%b-%Y').strftime('%m/%d/%Y')

希望这有帮助。你知道吗

我特别喜欢dateparser软件包。它使解析日期的第一步变得轻而易举。只要向它抛出一个有点像日期的字符串,或者对时间的引用,它就会为您将它转换成datetime。你知道吗

$ pip install dateparser

安装后:

import dateparser
from datetime import datetime

DB_date = "03-NOV-2016"
date = dateparser.parse(DB_date)

print datetime.datetime.strftime(date, '%m/%-d/%Y')

# Output: 11/3/2016

相关问题 更多 >

    热门问题