【问题标题】:I can't change the date format with python datetime [duplicate]我无法使用 python datetime 更改日期格式 [重复]
【发布时间】:2021-04-09 17:24:49
【问题描述】:

我有一个数据框,其中包含字符串模式下的日期值列。我想将它转换为日期时间,但我根本做不到。

我首先尝试让 datetime 函数自动检测它,但它不能。我也尝试过手动操作,但我也没有找到解决方案。 日期格式为“1 Ago 2020”,月份为西班牙语格式,同时,如您所见,它不包含直到 9 日的双 0。

我使用了不同的代码,但这里我展示了一些示例。

import pandas as pd 
import datetime
dfweight = pd.read_csv('data_weight.csv') 
pd.to_datetime(dfweight['Fecha'], format='%d %b, %Y')

他扔的地方:ValueError: time data '12 May 2020' does not match format '%d %b, %Y' (match)

我还尝试添加 # (% # d),因此它不会像我在某些 cmets 中读取的那样显示 0 到 9,但它会显示以下错误。

ValueError: '#' is a bad directive in format '% # d% b,% Y'

如果有人可以帮助我,我提前感谢你,因为我被阻止了。 提前致谢

【问题讨论】:

标签: python string date datetime type-conversion


【解决方案1】:

由于您使用的是西班牙语格式,因此您需要设置西班牙语 locale

  1. 在你的shell中,运行locale-gen。这可确保您拥有必要的本地化文件。
  >> sudo locale-gen es_ES.UTF-8
Generating locales (this might take a while)...
  es_ES.UTF-8... done
Generation complete.
  1. 在python中,首先设置语言环境。然后打电话给datetime.datetime.strptime。如果您为您的 date format code 传递正确的字符串(如 "%d %b %Y"),则 0 应该无关紧要。
  >> python3
Python 3.7.4 (default, Aug 13 2019, 20:35:49)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import locale
>>> import datetime
>>> locale.setlocale(locale.LC_TIME, 'es_ES.UTF-8')
'es_ES.UTF-8'
>>> datetime.datetime.strptime("1 Ago 2020", "%d %b %Y")
datetime.datetime(2020, 8, 1, 0, 0)
>>> datetime.datetime.strptime("09 Ago 2020", "%d %b %Y")
datetime.datetime(2020, 8, 9, 0, 0)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-30
    • 2023-01-25
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多