【问题标题】:How to convert integer into Month & Year format如何将整数转换为月和年格式
【发布时间】:2019-12-02 04:40:55
【问题描述】:

我有一个 Excel CSV 数据集,其中索引由日期表示,但格式如下:

201001
201002
201003 and so on.. 

所以它的格式是 YYYYMM。我需要在 Python 中将其转换为datetime 格式。

【问题讨论】:

  • 当月的这一天你应该得到什么?
  • year,month = divmod(n,100)
  • @Andrei 我不需要每月的哪一天。但出于编码目的,我可以将其作为每个月的 15 日。

标签: python datetime indexing formatting monthcalendar


【解决方案1】:

您可以使用strptime() 将这些转换为日期时间。

from datetime import datetime 

data = ['201001', '201002', '201003']
dt = [datetime.strptime(s, '%Y%m') for s in data] 

输出

[datetime.datetime(2010, 1, 1, 0, 0),
 datetime.datetime(2010, 2, 1, 0, 0),
 datetime.datetime(2010, 3, 1, 0, 0)]

字符串'%Y%m 告诉函数日期格式为YYYYMM。在strftime.org 有一个方便的strftimestrptime 指令参考。

编辑:

如果您的数据类是浮点数或整数,您首先需要将它们转换为字符串,然后才能使用strptime()。为此,您只需在列表理解中调用 str()

data = [201001, 201002, 201003]
dt = [datetime.strptime(str(s), '%Y%m') for s in data] 

【讨论】:

  • 我收到一个错误。 (strptime() 参数 1 必须是 str,而不是 int)。在这里,我正在尝试转换数据集的整个列。
  • 您的数据是整数格式,而不是字符串。将此行 dt = [datetime.strptime(s, '%Y%m') for s in data] 更改为 dt = [datetime.strptime(str(s), '%Y%m') for s in data] 。这将在格式化之前将整数转换为字符串。我已经编辑了答案以显示这一点。
  • 虽然编辑的没有任何错误,但是所有数据点的输出都是一样的。让我在这里给你实际的表格。我有一个“数据集”,其中有一列“日期”,其中包含日期的整数格式。而且我必须转换整个列,所以根据你的代码,我正在写: dataset.Date=[datetime.strptime(str(s), '%Y%m') for s in dataset.Date] 我可能是错了,实际上我是 python 和东西的新手。所以请不要介意我的小错误。
  • @SpandanRout dataset 是什么意思?它是什么数据结构?
  • 它是一个名为“Dataset”的数据框
【解决方案2】:

试试:

dd = 201001
dd = str(dd)
yer=dd[:4]
mn=dd[4:]
newformat=str(yer)+'-'+str(mn)

【讨论】:

  • 这不会创建任何类型的日期对象,只是一个中间有破折号的字符串......
【解决方案3】:

使用此代码:

from datetime import date
myint=201001
mydate=date(myint//100, myint%100, 1)

【讨论】:

    猜你喜欢
    • 2015-04-29
    • 1970-01-01
    • 1970-01-01
    • 2021-04-12
    • 1970-01-01
    • 2021-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多