Convert date to datetime in Python

后端 未结 10 2466
感动是毒
感动是毒 2020-11-28 17:10

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 giv

10条回答
  •  情书的邮戳
    2020-11-28 18:09

    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...

提交回复
热议问题