I didn't realize this, but apparently Python's strftime
function doesn't support dates before 1900:
>>> from datetime import datetime
>>> d = datetime(1899, 1, 1)
>>> d.strftime('%Y-%m-%d')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: year=1899 is before 1900; the datetime strftime() methods require year >= 1900
I'm sure I could hack together something myself to do this, but I figure the strftime
function is there for a reason (and there also is a reason why it can't support pre-1900 dates). I need to be able to support dates before 1900. I'd just use str
, but there's too much variation. In other words, it may or may not have microseconds or it may or may not have a timezone. Is there any solution to this?
If it makes a difference, I'm doing this so that I can write the data to a text file and load it into a database using Oracle SQL*Loader.
I essentially ended up doing Alex Martelli's answer. Here's a more complete implementation:
>>> from datetime import datetime
>>> d = datetime.now()
>>> d = d.replace(microsecond=0, tzinfo=None)
>>> str(d)
'2009-10-29 11:27:27'
The only difference is that str(d)
is equivalent to d.isoformat(' ')
.
The documentation seems pretty clear about this:
So there isn't going to be a solution that uses
strftime()
. Luckily, it's pretty straightforward to do this "by hand":This is the "feature" of the ctime library (UTF). Also You may have problem above 2038.
isoformat works on
datetime
instances w/o limitation of range:If you need a different-format string it's not too hard to slice, dice and remix pieces of the string you get from
isoformat
, which is very consistent (YYYY-MM-DDTHH:MM:SS.mmmmmm
, with the dot and following microseconds omitted if microseconds are zero).mxDateTime
can handle arbitrary dates. Python'stime
anddatetime
modules use UNIX timestamps internally, that's why they have limited range.This is from the matplotlib source. Could provide a good starting point for rolling your own.