Python日期字符串到日期对象

    技术2022-07-11  122

    本文翻译自:Python date string to date object

    How do I convert a string to a date object in python? 如何在python中将字符串转换为日期对象?

    The string would be: "24052010" (corresponding to the format: "%d%m%Y" ) 该字符串将是: "24052010" (对应格式: "%d%m%Y" )

    I don't want a datetime.datetime object, but rather a datetime.date. 我不想要datetime.datetime对象,而是datetime.date。


    #1楼

    参考:https://stackoom.com/question/BlPQ/Python日期字符串到日期对象


    #2楼

    import datetime datetime.datetime.strptime('24052010', '%d%m%Y').date()

    #3楼

    You can use strptime in the datetime package of Python: 您可以在Python的datetime包中使用strptime :

    >>> import datetime >>> datetime.datetime.strptime('24052010', "%d%m%Y").date() datetime.date(2010, 5, 24)

    #4楼

    Directly related question: 直接相关的问题:

    What if you have 怎么样?

    datetime.datetime.strptime("2015-02-24T13:00:00-08:00", "%Y-%B-%dT%H:%M:%S-%H:%M").date()

    and you get: 你得到:

    Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python2.7/_strptime.py", line 308, in _strptime format_regex = _TimeRE_cache.compile(format) File "/usr/local/lib/python2.7/_strptime.py", line 265, in compile return re_compile(self.pattern(format), IGNORECASE) File "/usr/local/lib/python2.7/re.py", line 194, in compile return _compile(pattern, flags) File "/usr/local/lib/python2.7/re.py", line 251, in _compile raise error, v # invalid expression sre_constants.error: redefinition of group name 'H' as group 7; was group 4

    and you tried: 你尝试过:

    <-24T13:00:00-08:00", "%Y-%B-%dT%HH:%MM:%SS-%HH:%MM").date()

    but you still get the traceback above. 但你仍然得到上面的追溯。

    Answer: 回答:

    >>> from dateutil.parser import parse >>> from datetime import datetime >>> parse("2015-02-24T13:00:00-08:00") datetime.datetime(2015, 2, 24, 13, 0, tzinfo=tzoffset(None, -28800))

    #5楼

    Use time module to convert data. 使用时间模块转换数据。

    Code snippet: 代码段:

    import time tring='20150103040500' var = int(time.mktime(time.strptime(tring, '%Y%m%d%H%M%S'))) print var

    #6楼

    There is another library called arrow really great to make manipulation on python date. 还有另一个名为arrow库非常适合在python日期进行操作。

    import arrow import datetime a = arrow.get('24052010', 'DMYYYY').date() print(isinstance(a, datetime.date)) # True
    Processed: 0.022, SQL: 9