Jonathan Paz
Jonathan Paz

Reputation: 1

How can I capitalize day and month in a .strftime?

I have this Python code that gives me the complete date, before it gave me everything in lower case, but here I found that I could put .capitalize ()

And towards the first letter of the day and month in capital letters, the problem is that it only works with the day, the first letter of the month is still my letter.

How can I make the first letter of the day and the first letter of the month uppercase?

def nowISO(self):
    """Return the current utc time in ISO8601 timestamp format."""

    return datetime.utcnow().isoformat()

def ISOtoHuman(self, date: str, language: str):
    """Return the provided ISO8601 timestamp in human-readable format."""

    try:
        locale.setlocale(locale.LC_ALL, 'es_MX.UTF-8')
    except locale.Error:
        log.warn(f"Unsupported locale configured, using system default")

    try:
        # Unix-supported zero padding removal
        return datetime.strptime(date, "%Y-%m-%d").strftime("%A, %-d, de %B, del %Y").capitalize()
    except ValueError:
        try:
            # Windows-supported zero padding removal
            return datetime.strptime(date, "%Y-%m-%d").strftime("%A %#d de %B del %Y").capitalize()
        except Exception as e:
            log.error(self, f"Failed to convert to human-readable time, {e}")

Example of the current result:

Lunes 26 de octubre del 2020

Upvotes: -1

Views: 1425

Answers (2)

Jonathan Paz
Jonathan Paz

Reputation: 1

I found the solution, it was just to change the .capitalize () function for the .title () function

New output

thx all

Upvotes: 0

rioV8
rioV8

Reputation: 28783

I don't know the default for your locale but you could try

datetime.strptime(date, "%Y-%m-%d").strftime("%A, %-d, de %B, del %Y")

If that returns lowercase versions than you can cut the date string, capitalise each part and join them together

' '.join( map(lambda s: s.capitalize(), datetime.strptime(date, "%Y-%m-%d").strftime("%A %-d de@@%B del %Y").split('@@') ) )

and

' '.join( map(lambda s: s.capitalize(), datetime.strptime(date, "%Y-%m-%d").strftime("%A %#d de@@%B del %Y").split('@@') ) )

Upvotes: 1

Related Questions