简体   繁体   中英

How to initialize datetime 0000-00-00 00:00:00 in Python?

I've been trying to use the datetime library in python to create a datetime object with this value: '0000-00-00 00:00:00'. However, I keep getting an error that the year is out of range. How can I properly initialize this?

There is no year 0, because people couldn't figure out how to count properly back then.

The closest you can get:

>>> from datetime import datetime
>>> datetime.min
datetime.datetime(1, 1, 1, 0, 0)

In datetime , the constant for MINYEAR is 1:

datetime.MINYEAR

The smallest year number allowed in a date or datetime object. MINYEAR is 1.

To initialize the earliest possible date you would do:

import datetime

earliest_date = datetime.datetime.min 
# OR
earliest_date = datetime.datetime(1,1,1,0,0)

print earliest_date.isoformat()

Which outputs:

0001-01-01T00:00:00

"How to initialize datetime 0000-00-00 00:00:00 in Python?"

No allowed, see manual datetime.

Alternative solution to the question is the minimum datetime:

>>> datetime.datetime.combine(datetime.date.min, datetime.time.min)
datetime.datetime(1, 1, 1, 0, 0)

found while reading: https://docs.python.org/3.7/library/datetime.html#module-datetime

Maybe this is something that can help.

var = datetime(1,1,1,0,0) - datetime(1,1,1,0,0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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