简体   繁体   English

Python String to dateTime转换

[英]Python String to dateTime conversion

I have a string like 我有一个字符串

a = "datetime.datetime(2009,04,01)"

I would like to convert this to a datetime object in python. 我想将它转换为python中的datetime对象。 How should I proceed? 我该怎么办?

The code in the previous answer would work, but using eval is considered risky, because an unexpected input could have disastrous consequences. 上一个答案中的代码可以使用,但使用eval被认为是有风险的,因为意外的输入可能会带来灾难性的后果。 ( Here 's more info on why eval can be dangerous.) 这里有关于为什么eval可能有危险的更多信息。)

A better option here is to use Python's strptime method: 这里更好的选择是使用Python的strptime方法:

from datetime import datetime

datetime_string = "datetime.datetime(2017, 3, 31)"
format = "datetime.datetime(%Y, %m, %d)"
datetime_object = datetime.strptime(datetime_string, format)

There are lots of different formats you can use for parsing datetimes from strings. 您可以使用许多不同的格式来解析字符串中的日期时间。 You may want to check out the docs: https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior 您可能需要查看文档: https//docs.python.org/2/library/datetime.html#strftime-strptime-behavior

you could use eval. 你可以使用eval。 eval lets run python code within python program eval允许在python程序中运行python代码

a = "datetime.datetime(2009,04,01)" 
import datetime
a = eval(a)
print a
print type(a)

will result in 会导致

2009-04-01 00:00:00
<type 'datetime.datetime'>

You can use eval 你可以使用eval

eval('datetime.datetime(2009, 1, 1)')

You'll have to make sure datetime is imported first 您必须首先确保导入datetime时间

>>> import datetime
>>> d = datetime.datetime(2009, 1, 1)
>>> repr(d)
'datetime.datetime(2009, 1, 1, 0, 0)`
>>> eval(repr(d))
datetime.datetime(2009, 1, 1, 0, 0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM