Python date string to date object

2019-01-01 06:29发布

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.

标签: python date
7条回答
笑指拈花
2楼-- · 2019-01-01 07:02
import datetime
datetime.datetime.strptime('24052010', '%d%m%Y').date()
查看更多
泪湿衣
3楼-- · 2019-01-01 07:06

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")
查看更多
心情的温度
4楼-- · 2019-01-01 07:08

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楼-- · 2019-01-01 07:08

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楼-- · 2019-01-01 07:09

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
查看更多
孤独总比滥情好
7楼-- · 2019-01-01 07:18

You can use strptime in the datetime package of Python:

>>> datetime.datetime.strptime('24052010', "%d%m%Y").date()
datetime.date(2010, 5, 24)
查看更多
登录 后发表回答