将字符串转换为日期类型python
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15557828/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
convert string to date type python
提问by Alfredo Solís
How do I convert a string to a date object in python?
如何在python中将字符串转换为日期对象?
The string would be: "30-01-12" (corresponding to the format: "%d-%m-%y")
字符串将是:“30-01-12”(对应于格式:“%d-%m-%y”)
I don't want a datetime.datetime object, but rather a datetime.date
我不想要一个 datetime.datetime 对象,而是一个 datetime.date
采纳答案by Martijn Pieters
You still use datetime.datetimebut then request just the .date()portion:
您仍然使用datetime.datetime但随后只请求.date()部分:
datetime.datetime.strptime('30-01-12', '%d-%m-%y').date()
Demonstration:
示范:
>>> import datetime
>>> datetime.datetime.strptime('30-01-12', '%d-%m-%y').date()
datetime.date(2012, 1, 30)
回答by jbuchman
This should work:
这应该有效:
import datetime
s = "30-01-12"
slist = s.split("-")
sdate = datetime.date(int(slist[2]),int(slist[0]),int(slist[1]))
回答by Davit
from datetime import datetime,date
date_str = '30-01-12'
formatter_string = "%d-%m-%y"
datetime_object = datetime.strptime(date_str, formatter_string)
date_object = datetime_object.date()

