You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python异步函数中获取当前日期和时间?

在Python异步函数中获取当前日期和时间

直接用Python标准库datetime就能搞定,它的同步方法在异步函数里可以安全调用——这些操作都是轻量CPU操作,不会阻塞异步事件循环。

常用获取方式

  • 获取本地时间:datetime.datetime.now()
  • 获取UTC时间(推荐存入数据库,避免时区混乱):datetime.datetime.utcnow()
  • 格式化时间为字符串(自定义格式):用strftime()方法,比如current_time.strftime("%Y-%m-%d %H:%M:%S")

结合你的代码示例

先导入datetime模块,然后在函数里按需使用:

import datetime
from aiogram import types
# 其他必要导入...

@dp.message_handler(commands=['start'])
async def command_start(message: types.Message):
    # 获取用户数据
    person_id = message.from_user.id
    person_name = message.from_user.full_name

    # 获取当前UTC时间(适合存入数据库)
    current_utc_time = datetime.datetime.utcnow()
    # 或者获取本地时间:current_local_time = datetime.datetime.now()
    # 格式化本地时间为可读字符串:formatted_time = current_local_time.strftime("%Y年%m月%d日 %H:%M:%S")

    connection_pool = await create_asyncpg_connection_pool()

    if person_id and person_name:
        try:
            async with connection_pool.acquire() as connection:
                async with connection.transaction():
                    user_exists = await connection.fetchval("SELECT 1 FROM user_data WHERE user_id = $1", person_id)
                    if not user_exists:
                        # 插入用户时同时保存创建时间(假设表中有create_time字段)
                        await connection.execute(
                            "INSERT INTO user_data (user_id, username, create_time) VALUES ($1, $2, $3)",
                            person_id, person_name, current_utc_time
                        )
        except Exception as error:
            print(error)

    # 回复消息中带上格式化后的时间
    formatted_time = current_utc_time.strftime("%Y-%m-%d %H:%M:%S UTC")
    await message.answer(f"欢迎使用!当前UTC时间:{formatted_time}")

注意事项

  • 如果你用的是PostgreSQL(搭配asyncpg),直接传入datetime对象即可,驱动会自动完成类型转换
  • 若要处理时区,推荐使用带时区的时间对象:datetime.datetime.now(datetime.timezone.utc),避免时间歧义
  • 无需担心同步方法在异步函数中的使用,datetime的操作都是瞬时完成的,不会影响异步流程

内容的提问来源于stack exchange,提问作者fishlover12345

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 12:51:02