问题:在Python中将日期转换为日期时间

是否有一个内置的转换方法datedatetime在Python,例如获得datetime在指定日期的午夜?相反的转换很容易:datetime有一个.date()方法。

我真的必须手动打电话datetime(d.year, d.month, d.day)吗?

Is there a built-in method for converting a date to a datetime in Python, for example getting the datetime for the midnight of the given date? The opposite conversion is easy: datetime has a .date() method.

Do I really have to manually call datetime(d.year, d.month, d.day)?


回答 0

您可以使用;现在,您创建一个datetime.time初始化为午夜的对象。

from datetime import date
from datetime import datetime

dt = datetime.combine(date.today(), datetime.min.time())

You can use ; for the time, you create a datetime.time object initialized to midnight.

from datetime import date
from datetime import datetime

dt = datetime.combine(date.today(), datetime.min.time())

回答 1

尽管我确实相信您提到(和不喜欢)的方法是最易读的方法,但是有几种方法。

>>> t=datetime.date.today()
>>> datetime.datetime.fromordinal(t.toordinal())
datetime.datetime(2009, 12, 20, 0, 0)
>>> datetime.datetime(t.year, t.month, t.day)
datetime.datetime(2009, 12, 20, 0, 0)
>>> datetime.datetime(*t.timetuple()[:-4])
datetime.datetime(2009, 12, 20, 0, 0)

依此类推-但基本上它们都取决于从date对象中适当地提取信息并将其犁入合适的ctor或classfunction中datetime

There are several ways, although I do believe the one you mention (and dislike) is the most readable one.

>>> t=datetime.date.today()
>>> datetime.datetime.fromordinal(t.toordinal())
datetime.datetime(2009, 12, 20, 0, 0)
>>> datetime.datetime(t.year, t.month, t.day)
datetime.datetime(2009, 12, 20, 0, 0)
>>> datetime.datetime(*t.timetuple()[:-4])
datetime.datetime(2009, 12, 20, 0, 0)

and so forth — but basically they all hinge on appropriately extracting info from the date object and ploughing it back into the suitable ctor or classfunction for datetime.


回答 2

可接受的答案是正确的,但我宁愿避免使用datetime.min.time()它,因为它对我的确切作用并不明显。如果对您而言显而易见,那么您将拥有更多权力。我也对timetuple方法和对订购的依赖的看法。

我认为,在不依赖读者非常熟悉datetime模块API的情况下,最易读,明确的方式是:

from datetime import date, datetime
today = date.today()
today_with_time = datetime(
    year=today.year, 
    month=today.month,
    day=today.day,
)

这就是我对“明确胜于隐含”的看法。

The accepted answer is correct, but I would prefer to avoid using datetime.min.time() because it’s not obvious to me exactly what it does. If it’s obvious to you, then more power to you. I also feel the same way about the timetuple method and the reliance on the ordering.

In my opinion, the most readable, explicit way of doing this without relying on the reader to be very familiar with the datetime module API is:

from datetime import date, datetime
today = date.today()
today_with_time = datetime(
    year=today.year, 
    month=today.month,
    day=today.day,
)

That’s my take on “explicit is better than implicit.”


回答 3

您可以使用date.timetuple()method和unpack运算符*

args = d.timetuple()[:6]
datetime.datetime(*args)

You can use the date.timetuple() method and unpack operator *.

args = d.timetuple()[:6]
datetime.datetime(*args)

回答 4

今天是2016年,我认为pandas Timestamp提供了最干净的解决方案:

from datetime import date
import pandas as pd
d = date.today()
pd.Timestamp(d)

时间戳等于日期时间的大熊猫,并且在大多数情况下可以互换。校验:

from datetime import datetime
isinstance(pd.Timestamp(d), datetime)

但是,如果您真的想要一个普通的日期时间,您仍然可以执行以下操作:

pd.Timestamp(d).to_datetime()

时间戳比日期时间强大得多,尤其是在处理时区时。实际上,时间戳记是如此强大,以至于它们的文献记录如此之少,实在令人遗憾。

Today being 2016, I think the cleanest solution is provided by pandas Timestamp:

from datetime import date
import pandas as pd
d = date.today()
pd.Timestamp(d)

Timestamp is the pandas equivalent of datetime and is interchangable with it in most cases. Check:

from datetime import datetime
isinstance(pd.Timestamp(d), datetime)

But in case you really want a vanilla datetime, you can still do:

pd.Timestamp(d).to_datetime()

Timestamps are a lot more powerful than datetimes, amongst others when dealing with timezones. Actually, Timestamps are so powerful that it’s a pity they are so poorly documented…


回答 5

尚未提到的将日期转换为日期时间的一种方法:

from datetime import date, datetime
d = date.today()
datetime.strptime(d.strftime('%Y%m%d'), '%Y%m%d')

One way to convert from date to datetime that hasn’t been mentioned yet:

from datetime import date, datetime
d = date.today()
datetime.strptime(d.strftime('%Y%m%d'), '%Y%m%d')

回答 6

您可以使用 easy_date使其变得容易:

import date_converter
my_datetime = date_converter.date_to_datetime(my_date)

You can use easy_date to make it easy:

import date_converter
my_datetime = date_converter.date_to_datetime(my_date)

回答 7

如果您需要快速操作,请datetime_object.date()给您一个datetime对象的日期。

If you need something quick, datetime_object.date() gives you a date of a datetime object.


回答 8

我是Python的新手。但是这段代码对我有用,它将我提供的指定输入转换为datetime。这是代码。如我错了请纠正我。

import sys
from datetime import datetime
from time import mktime, strptime

user_date = '02/15/1989'
if user_date is not None:
     user_date = datetime.strptime(user_date,"%m/%d/%Y")
else:
     user_date = datetime.now()
print user_date

I am a newbie to Python. But this code worked for me which converts the specified input I provide to datetime. Here’s the code. Correct me if I’m wrong.

import sys
from datetime import datetime
from time import mktime, strptime

user_date = '02/15/1989'
if user_date is not None:
     user_date = datetime.strptime(user_date,"%m/%d/%Y")
else:
     user_date = datetime.now()
print user_date

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。