【问题标题】:How can I convert a string into a date object and get year, month and day separately?如何将字符串转换为日期对象并分别获取年、月和日?
【发布时间】:2012-09-07 23:01:12
【问题描述】:

如果我说这个字符串“2008-12-12 19:21:10”,我如何将它转换为日期并分别从创建的对象中获取年、月和日?

【问题讨论】:

  • 我忘了说我想得到类似的东西: object.getYear() #will print the string'2008' 或类似的东西
  • 您可以轻松创建一个使用datetime 的类或包含datetime.datetime 实例并提供get_year() 方法。

标签: python string datetime


【解决方案1】:

https://www.tutorialspoint.com/python/time_strptime.htm 在这里您可以找到 strptime() 方法的完整说明。您可以在其中找到所有类型的字符串。 例如:- 转换这样的字符串 '15-MAY-12'

>>>from datetime import datetime
>>>datestring = "15-MAY-12"
>>>dt = datetime.strptime(datestring, '%d-%b-%Y')
>>>print(dt.year, dt.month, dt.day)
 2012 MAY 15

【讨论】:

  • 此代码出错;您必须将 Y 更改为 y。正如下面的答案所指出的,'%y 是两位数的年份符号,%Y 是四位数的一年'。
【解决方案2】:

要补充一点;注意%y是两位数的年份符号%Y是四位数的一:

import datetime

datestring = '15-MAY-12'
print(datetime.datetime.strptime(datestring, '%d-%b-%y'))
>>> datetime.datetime(2012, 5, 15, 0, 0)

datestring = '15-MAY-2012'    
print(datetime.datetime.strptime(datestring, '%d-%b-%Y'))
>>> datetime.datetime(2012, 5, 15, 0, 0)

【讨论】:

    【解决方案3】:

    毫秒

    >>> from datetime import datetime
    >>> datestring = "2018-04-11 23:36:18.886585"
    >>> dt = datetime.strptime(datestring, '%Y-%m-%d %H:%M:%S.%f')
    >>> print dt.year, dt.month, dt.day
    2018 04 11
    

    【讨论】:

      【解决方案4】:

      使用datetime.datetime.strptime() function

      from datetime import datetime
      dt = datetime.strptime(datestring, '%Y-%m-%d %H:%M:%S')
      

      现在您有一个datetime.datetime 对象,它具有.year.month.day 属性:

      >>> from datetime import datetime
      >>> datestring = "2008-12-12 19:21:10"
      >>> dt = datetime.strptime(datestring, '%Y-%m-%d %H:%M:%S')
      >>> print dt.year, dt.month, dt.day
      2008 12 12
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-07-08
        • 1970-01-01
        • 2020-08-26
        • 1970-01-01
        • 2016-10-14
        • 1970-01-01
        • 1970-01-01
        • 2011-05-11
        相关资源
        最近更新 更多