Reputation: 2592
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?
Upvotes: 24
Views: 48557
Reputation: 11
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.
Upvotes: 1
Reputation: 1283
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)
Upvotes: 0
Reputation: 11
"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
Upvotes: 0
Reputation: 18221
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
Upvotes: 8
Reputation: 363113
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)
Upvotes: 42