Python date string to date object

2019-01-01 06:58发布

问题:

How do I convert a string to a date object in python?

The string would be: \"24052010\" (corresponding to the format: \"%d%m%Y\")

I don\'t want a datetime.datetime object, but rather a datetime.date.

回答1:

You can use strptime in the datetime package of Python:

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


回答2:

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


回答3:

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))


回答4:

If you are lazy and don\'t want to fight with string literals, you can just go with the parser module.

from dateutil import parser
dt = parser.parse(\"Jun 1 2005  1:33PM\")
print(dt.year, dt.month, dt.day,dt.hour, dt.minute, dt.second)
>2005 6 1 13 33 0

Just a side note, as we are trying to match any string representation, it is 10x slower than strptime



回答5:

There is another library called arrow really great to make manipulation on python date.

import arrow
import datetime

a = arrow.get(\'24052010\', \'DMYYYY\').date()
print(isinstance(a, datetime.date)) # True


回答6:

you have a date string like this, \"24052010\" and you want date object for this,

from datetime import datetime
cus_date = datetime.strptime(\"24052010\", \"%d%m%Y\").date()

this cus_date will give you date object.

you can retrieve date string from your date object using this,

cus_date.strftime(\"%d%m%Y\")


回答7:

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


标签: python date