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

Question:

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?

Asked By: user3802348

||

Answers:

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)
Answered By: wim

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
Answered By: rouble

"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

Answered By: Aap1

Old question, but I needed a minimum datetime object which is POSIX compliant, so I found I could get that from

datetime.utcfromtimestamp(0)

which gives 1st Jan 1970 00:00:00:0000. But you need to be really careful with this, the datetime object returned is naive (no tz info).

Add utc timezone when using this:

datetime.utcfromtimestamp(0).replace(tzinfo=timezone.utc)
[>] datetime.datetime(1970, 1, 1, 0, 0, tzinfo=datetime.timezone.utc)

Oddly, if you have to convert back to POSIX with timestamp() from a naive datetime, it throws an error for anything less than 2nd Jan 1970 1am

datetime(1970,1,2,1,0,0).timestamp()
[>] 86400.0

You can fix this by adding timezone:

datetime(1970,1,1).replace(tzinfo=timezone.utc).timestamp()
[>] 0.0

Also, in version 3.2, strftime() method was restricted to years >= 1000. (ref)

Answered By: Richard Allen

If you want to initialize a datetime.timedelta object, you can use the following statement:

lapseTime = datetime.now() - datetime.now()

lapseTime will be initialized to datetime.timedelta(0). You can then use lapseTime to do arithmetic calculations with other datetime objects.

Answered By: Charles Wang
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.