Home > Back-end >  Does the datetime.datetime.ctime() function return a fixed width string?
Does the datetime.datetime.ctime() function return a fixed width string?

Time:02-07

If I were to run the following code:

import datetime
dt = datetime.datetime.now()
date_str = dt.ctime()

Will the result of len(date_str) always be the same, regardless of when I happen to run the code? I think it will be, but I'm not certain. I looked at the datetime module reference but the relevant section says:

Return a string representing the date:

>>> from datetime import date
>>> date(2002, 12, 4).ctime()
'Wed Dec  4 00:00:00 2002'

d.ctime() is equivalent to:

time.ctime(time.mktime(d.timetuple()))

on platforms where the native C ctime() function (which time.ctime() invokes, but which date.ctime() does not invoke) conforms to the C standard.

But looking at the article on cppreference.com, the answer is less than clear to me. I did find a reference here which suggests that it will be a 24-character wide string, but I was hoping for a more official source or reference if possible. It's possible that I didn't delve far enough into the C-standard to divine the answer.

Also, based on that quote, does that mean the behavior might be platform-dependent? Or is it likely to be generally uniform outside of niche operating systems?

(yes I know that I can manually format to fixed-width, but I want to know whether the built-in one already is that way)

CodePudding user response:

I've looked up datetime in the source code of cpython on github. It is implemented as this:

    def ctime(self):
        "Return ctime() style string."
        weekday = self.toordinal() % 7 or 7
        return "%s %s - 00:00:00 d" % (
            _DAYNAMES[weekday],
            _MONTHNAMES[self._month],
            self._day, self._year)

with _DAYNAMES and _MONTHNAMES being:

_MONTHNAMES = [None, "Jan", "Feb", "Mar", "Apr", "May", "Jun",
                     "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
_DAYNAMES = [None, "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]

So I would think the length will always be the same. The only exception that I can think of is when weekday and self._month are set at 0, making them return None. Rather than a 3-string word, it returns a 4-string word in those cases. But since you always will use datetime.now(), this shouldn't be of any concern.

CodePudding user response:

It's fixed-width. You can see in the cppreference article you linked that the output of C ctime follows the format

Www Mmm dd hh:mm:ss yyyy\n

which is fixed-width. (Python doesn't include the trailing \n, but it's still fixed-width.)

You can also check the C standard directly and find that the standard-mandated output is fixed-width.

You can also check the implementation of datetime.ctime if you want to be extra sure.

Also, based on that quote, does that mean the behavior might be platform-dependent?

No. The behavior is platform-independent. The quote is saying that datetime.ctime behaves like the C standard mandated behavior of the C ctime function, even if the platform implementation of the C function does not conform to the C standard.

CodePudding user response:

Well, cppreference clearly states that the C standard requires ctime to return a 25 characters strings ending with a newline.

The resulting string has the following format:

Www Mmm dd hh:mm:ss yyyy\n

...

The function does not support localization.

The doc for the time module states (emphasize mine):

Most of the functions defined in this module call platform C library functions with the same name.

A ctime is required by C standard, it should be available on any platform. So it should be always used by time.ctime.

Let us go on:

time.ctime([secs])

...

If secs is not provided or None, the current time as returned by time() is used. ctime(secs) is equivalent to asctime(localtime(secs)). Locale information is not used by ctime().

and

time.asctime([t])

Convert a tuple or struct_time representing a time as returned by gmtime() or localtime() to a string of the following form: 'Sun Jun 20 23:21:05 1993'. The day field is two characters long and is space padded if the day is a single digit, e.g.: 'Wed Jun 9 04:26:40 1993'. ... Note: Unlike the C function of the same name, asctime() does not add a trailing newline.

So instead of the 25 characters string returned by the C function, the ctime or asctime functions of the Python standard library time module return a non localized 24 characters string.

So if you use CPython, and except on a specific system where the C standard library would be non conformant, you can trust time.ctime to always return a 24 character string.

And even if you use a different implementation (Jython, PyPy, etc.) the Python standard library documentation states that this non localized 24 characters string should be returned. So I cannot imagine a system returning a different size...

  •  Tags:  
  • Related