Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use datetime.strftime() on years before 1900? ("require year >= 1900")

I used : utctime = datetime.datetime(1601,1,1) + datetime.timedelta(microseconds = tup[5]) last_visit_time = "Last visit time:"+ utctime.strftime('%Y-%m-%d %H:%M:%S')

But I have the time of 1601, so the error show: ValueError: year=1601 is before 1900; the datetime strftime() methods require year >= 1900

I used python2.7, how can I make it? Thanks a lot!

like image 739
Alex Avatar asked Apr 21 '12 23:04

Alex


People also ask

What does DateTime Strftime do?

The strftime() function is used to convert date and time objects to their string representation. It takes one or more input of formatted code and returns the string representation. Returns : It returns the string representation of the date or time object.

What can I use instead of Strftime?

The strftime is obsolete and DateTime::format() provide a quick replacement and IntlDateFormatter::format() provied a more sophisticated slution.

What does Strftime return in Python?

The strftime() method returns a string representing date and time using date, time or datetime object.

What is the difference between Strptime and Strftime?

strptime is short for "parse time" where strftime is for "formatting time". That is, strptime is the opposite of strftime though they use, conveniently, the same formatting specification.


2 Answers

You can do the following:

>>> utctime.isoformat() '1601-01-01T00:00:00.000050' 

Now if you want to have exactly the same format as above:

iso = utctime.isoformat() tokens = iso.strip().split("T") last_visit_time = "Last visit time: %s %s" % (tokens[0], tokens[1].strip().split(".")[0]) 

Not that there seems to be a patch for strftime to fix this behavior here (not tested)

like image 87
Charles Menguy Avatar answered Oct 03 '22 02:10

Charles Menguy


the isoformat method accepts a parameter specifing the character(s) dividing the date part from the time part of a datetime obj in its representation. Therefore:

>>> utctime.isoformat(" ") '1601-01-01 00:00:00.000050' 

should do it. Furthermore, if you want to remove the microseconds you can operate a split.

>>> utctime.isoformat(" ").split(".")[0] '1601-01-01 00:00:00' 
like image 22
Michele Soltanto Avatar answered Oct 03 '22 01:10

Michele Soltanto