如何从python中的“16SEP2012”创建日期时间对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18684397/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:27:05  来源:igfitidea点击:

How to create datetime object from "16SEP2012" in python

pythonstringdatetime

提问by alwbtc

I can create datetime objects in python this way:

我可以通过这种方式在 python 中创建日期时间对象:

import datetime

new_date= datetime.datetime(2012,09,16)

How can I create same datetimeobject from a string in this format: "16SEP2012"?

如何datetime从以下格式的字符串创建相同的对象:"16SEP2012"

采纳答案by falsetru

Use datetime.datetime.strptime:

使用datetime.datetime.strptime

>>> datetime.datetime.strptime('16Sep2012', '%d%b%Y')
datetime.datetime(2012, 9, 16, 0, 0)