如何获取当前时间?
当前回答
如果需要当前时间作为时间对象:
>>> import datetime
>>> now = datetime.datetime.now()
>>> datetime.time(now.hour, now.minute, now.second)
datetime.time(11, 23, 44)
其他回答
如果需要当前时间作为时间对象:
>>> import datetime
>>> now = datetime.datetime.now()
>>> datetime.time(now.hour, now.minute, now.second)
datetime.time(11, 23, 44)
我们可以使用datetime模块来完成
>>> from datetime import datetime
>>> now = datetime.now() #get a datetime object containing current date and time
>>> current_time = now.strftime("%H:%M:%S") #created a string representing current time
>>> print("Current Time =", current_time)
Current Time = 17:56:54
此外,我们可以使用pytZ模块获取当前时间zome。
>>> from pytz import timezone
>>> import pytz
>>> eastern = timezone('US/Eastern')
>>> eastern.zone
'US/Eastern'
>>> amsterdam = timezone('Europe/Amsterdam')
>>> datetime_eu = datetime.now(amsterdam)
>>> print("Europe time::", datetime_eu.strftime("%H:%M:%S"))
Europe time:: 14:45:31
如果您将其用于django datetime有时在服务器上无法工作,所以我建议使用时区
但要使用django时区,您应该在设置中设置您的国家/地区时区代码。py
TIME_ZONE = 'Asia/Tashkent'
那你就可以用它了
from django.utils import timezone
timezone.now() // for date time
timezone.now().year // for yaer
timezone.now().month // for month
timezone.now().day // for day
timezone.now().date // for date
timezone.now().hour // for hour
timezone.now().weekday // for minute
或者如果您想在python上使用
import time
time.strftime('%X') // '13:12:47'
time.strftime('%x') // '01/20/22'
time.strftime('%d') // '20' day
time.strftime('%m') // '01' month
time.strftime('%y') // '20' year
time.strftime('%H') // '01' hour
time.strftime('%M') // '01' minute
time.strftime('%m') // '01' second
如果你经常使用panda,你可以使用Timestamp,它相当于Python的Datetime:
In [1]: import pandas as pd
In [2]: pd.Timestamp.now()
Out[2]: Timestamp('2022-06-21 21:52:50.568788')
只是时间:
In [3]: pd.Timestamp.now().strftime("%H:%M:%S")
Out[3]: '21:53:01'
使用time.strftime():
>>> from time import gmtime, strftime
>>> strftime("%Y-%m-%d %H:%M:%S", gmtime())
'2009-01-05 22:14:39'
推荐文章
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录
- 我如何告诉matplotlib我已经完成了一个情节?
- 如何在Python中记录源文件名称和行号