Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can i get current date and time inside async python-function?

I need to get current date and time in async function. How can i do so?

@dp.message_handler(commands=['start'])
async def command_start(message: types.message):
    # Получение данных о пользователе (id, name) для последующей записи в БД.
    person_id = message.from_user.id
    person_name = message.from_user.full_name

    # Создание пула соединений.
    connection_pool = await create_asyncpg_connection_pool()

    # Если person_id и person_name записаны, то далее происходит подключение к БД.
    if person_id and person_name:
        # Блок except необходим для корректного отображения ошибки.
        try:
            # Получение асинхронного соединения из пула.
            async with connection_pool.acquire() as connection:
                # Начало асинхронной транзакции. Объект cursor не требуется.
                async with connection.transaction():
                    # Проверка, существует ли пользователь в базе данных.
                    user_exists = await connection.fetchval("SELECT 1 FROM user_data WHERE user_id = $1", person_id)
                    # Если пользователь не существует, добавляем его в базу данных.
                    if not user_exists:
                        await connection.execute("INSERT INTO user_data (user_id, username) VALUES ($1, $2)", person_id,
                                                 person_name)
        except Exception as error:
            # Блок except необходим для корректного отображения ошибки.
            print(error)

    
    await message.answer(some text)

Didn’t try anything cuz of lack of information 🙁 Pls, help me. I’m new to python.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It gets the current date time:

now = datetime.now()
print("now =", now)

Or even you can format it with:

# dd/mm/YY H:M:S
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
print("date and time =", dt_string)

This is how to get the current date:

today = date.today()
print("Today's date:", today)

Its output looks like this:

Today’s date: 2022-12-27

Note that, this also works on "synchronized" code beside with the async code.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading