How to get the current time in Python

前端 未结 30 1438
滥情空心
滥情空心 2020-11-22 06:47

What is the module/method used to get the current time?

30条回答
  •  悲&欢浪女
    2020-11-22 07:26

    datetime.now() returns the current time as a naive datetime object that represents time in the local timezone. That value may be ambiguous e.g., during DST transitions ("fall back"). To avoid ambiguity either UTC timezone should be used:

    from datetime import datetime
    
    utc_time = datetime.utcnow()
    print(utc_time) # -> 2014-12-22 22:48:59.916417
    

    Or a timezone-aware object that has the corresponding timezone info attached (Python 3.2+):

    from datetime import datetime, timezone
    
    now = datetime.now(timezone.utc).astimezone()
    print(now) # -> 2014-12-23 01:49:25.837541+03:00
    

提交回复
热议问题