Convert sqlite tuple like ('Thu, 9 Jun 2022 12:55:10 +0000 (UTC)',) to date

Hello,

I have an tuple from sqlite like:

(‘Thu, 9 Jun 2022 12:55:10 +0000 (UTC)’,)

Anybody knows how to convert it easy to:
2022-06-09

Maybe as a date object? At the moment the source column in Sqlite is string.

Thank you in advance!

Best regards
Frank

What a terrible idea, storing a date as such a complicated string into a database!

It looks like the RFC2822 format. The standard library has a function for parsing this:
email.utils. parsedate (date)

2 Likes

@Apollo
For the fun, using strptime and strftime:

from datetime import datetime


def sqlite_dt_to_custom_dt(date: str, format: str):
    '''
    date: input date
    format: custom output format\n
    Converts string object to datetime object, and extract the date and/or time with custom format.
    '''
    return datetime.strptime(date, r'%a, %d %b %Y %H:%M:%S %z (%Z)').strftime(format)


# SQLite tuple
t = ('Thu, 9 Jun 2022 12:55:10 +0000 (UTC)',)


# Printing the result
print(sqlite_dt_to_custom_dt(t[0], r'%Y-%m-%d'))

I have to agree with @vbrozik , and you can use his suggestion like this:

from datetime import datetime
from email import utils


def sqlite_dt_to_custom_dt(date: str, format: str):
    '''
    date: input date
    format: custom output format\n
    Converts string object to datetime object, and extract the date and/or time with custom format.
    '''
    
    return datetime(*utils.parsedate(date)[:-2]).strftime(format)


# SQLite tuple
t = ('Thu, 9 Jun 2022 12:55:10 +0000 (UTC)',)


# Printing the result
print(sqlite_dt_to_custom_dt(t[0], r'%Y-%m-%d'))

Happy coding :slight_smile:

Cheers.

2 Likes

And then you can register a converter function using sqlite3.register_converter() and use column names in your query to automatically convert these strings to datetime objects when you fetch your result rows.

3 Likes