Python:将日期转换为日期时间的最有效方法 [英] Python: most efficient way to convert date to datetime

查看:79
本文介绍了Python:将日期转换为日期时间的最有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,我将日期转换为 datetime 的方式是:

In Python, I convert a date to datetime by:


  1. 日期转换为 string

  2. 字符串转换为 datetime

  1. converting from date to string
  2. converting from string to datetime

代码:

import datetime
dt_format="%d%m%Y"
my_date = datetime.date.today()
datetime.datetime.strptime(my_date.strftime(dt_format), dt_format)

我怀疑这远非最有效的方法。在Python中将日期转换为日期时间的最有效方法是什么?

I suspect this is far from the most efficient way to do this. What is the most efficient way to convert a date to datetime in Python?

推荐答案

使用 datetime.datetime.combine() 和一个时间对象, datetime.time.min 表示 00:00 并将与您的date-string-datetime路径的输出匹配: / p>

Use datetime.datetime.combine() with a time object, datetime.time.min represents 00:00 and would match the output of your date-string-datetime path:

datetime.datetime.combine(my_date, datetime.time.min)

演示:

>>> import datetime
>>> my_date = datetime.date.today()
>>> datetime.datetime.combine(my_date, datetime.time.min)
datetime.datetime(2013, 3, 27, 0, 0)

这篇关于Python:将日期转换为日期时间的最有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆