【问题标题】:Converting Object to datetime in Python在 Python 中将对象转换为日期时间
【发布时间】:2020-09-08 18:39:30
【问题描述】:

我有一串这种格式的系列:2017-12-04T08:30:00+11:00。我正在尝试将其转换为日期时间对象。以黄色突出显示。参见图片:

如何从开始、结束和更新的列中获取日期并将这些对象转换为日期?

我试过了:

def ISOtstr(iso):
    dcomponents = [1,1,1]
    dcomponents[0] = iso[:4]
    dcomponents[1] = iso[5:7]
    dcomponents[2] = iso[8:10]
    tcomponents = [1,1,1]
    tcomponents[0] = iso[11:13]
    tcomponents[1] = iso[14:16]
    tcomponents[2] = iso[17:19]
    d = dcomponents
    t = tcomponents
    string = "{}-{}-{} {}:{}:{}".format(d[0],d[1],d[2],t[0],t[1],t[2])
    return string
import datetime

string = a.iloc[1]['start']
date_string = ISOtstr(string)
date_obj = datetime.datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S')
print(date_obj)
print(type(date_obj)) 
for item in df['start'].iteritems():
    datetime.datetime.strptime(df['start'], "%a-%b-%d-%H-%M-%S-%Z-%Y")
import datetime

date_time_str = a['start']
date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f')
print('Date:', date_time_obj.date())
print('Time:', date_time_obj.time())
print('Date-time:', date_time_obj)

TypeError: strptime() 参数 1 必须是 str,而不是 Series

IPython 笔记本: https://drive.google.com/file/d/1YbQZOCxtLLUiB4YyivRhM5W6n6CVVh3y/view?usp=sharing

【问题讨论】:

    标签: python datetime


    【解决方案1】:

    pandas 有一个非常有用的pd.to_datetime 函数,它可以做你想做的事。

    【讨论】:

      【解决方案2】:

      您需要传递 datetime.datetime.strptime() 一个字符串,而不是系列。 df['start'] 正在索引您的 'start' 列。如果你想特别坚持使用 datetime 模块,你可以考虑使用 df.apply,或者迭代你的数据。

      但是,其他人在我之前提到过,pandas 有一个 built-in datetime method 可以完全按照您的意愿行事!

      首先(抱歉,现在没有太多时间!),您实际上需要将一系列 df 作为参数传递给 pandas 类,就像这样

      df['start']=pd.to_datetime(df['start'],format='%foo%bar)
      

      返回的对象将是您可以分配给“开始”系列的系列。

      【讨论】:

        【解决方案3】:

        在 Python 中有一个 dateutil module 可以完成所有神奇的日期解析工作:

        >>> import dateutil.parser
        >>> dateutil.parser.parse('2017-12-04T08:30:00+11:00')
        datetime.datetime(2017, 12, 4, 8, 30, tzinfo=tzoffset(None, 39600))
        

        【讨论】:

          猜你喜欢
          • 2017-01-08
          • 2016-11-14
          • 2019-05-20
          • 1970-01-01
          • 2011-12-02
          • 2018-11-03
          • 2019-04-27
          • 2020-04-03
          • 2010-12-06
          相关资源
          最近更新 更多