如何获取当前时间?
当前回答
对UTC日期时间、本地日期时间使用此方法,并转换上午和下午
import pytz
from datetime import datetime
#UTC Time
print("UTC Date and time")
epoch: datetime =datetime.now().replace(tzinfo=pytz.utc)
print(epoch)
#local date and time
print("Local Date and time")
today = datetime.now()
local_time = today.strftime("%Y-%M-%d:%H:%M:%S")
print(local_time)
#convert time to AM PM format
print("Date and time AM and PM")
now = today.strftime("%Y-%M-%d:%I:%M %p")
print(now)
其他回答
import datetime
import pytz # for timezone()
import time
current_time1 = datetime.datetime.now()
current_time2 = datetime.datetime.now(pytz.timezone('Asia/Taipei'))
current_time3 = datetime.datetime.utcnow()
current_time4 = datetime.datetime.now().isoformat()
current_time5 = time.gmtime(time.time())
print("datetime.datetime.now():", current_time1)
print("datetime.datetime.now(pytz.timezone('Asia/Taipei')):", current_time2)
print("datetime.utcnow():", current_time3)
print("datetime.datetime.now().isoformat():", current_time4)
print('time.gmtime(time.time()): ', current_time5)
如果你经常使用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'
您可以尝试以下操作
import datetime
now = datetime.datetime.now()
print(now)
or
import datetime
now = datetime.datetime.now()
print(now.strftime("%Y-%b-%d, %A %I:%M:%S"))
from datetime import datetime
datetime.now().strftime('%Y-%m-%d %H:%M:%S')
示例输出:“2013-09-18 11:16:32”
请参阅strftime指令列表。
推荐文章
- Numpy Max vs amax vs maximum
- 我应该在.gitignore文件中添加Django迁移文件吗?
- 每n行有熊猫
- 实例属性attribute_name定义在__init__之外
- 如何获取在Python中捕获的异常的名称?
- 第一次出现的值大于现有值的Numpy
- 如何从Python函数中返回两个值?
- 前一个月的Python日期
- Python中方括号括起来的列表和圆括号括起来的列表有什么区别?
- Python日志记录不输出任何东西
- 每n秒运行特定代码
- SQLAlchemy是否有与Django的get_or_create等价的函数?
- 如何将python datetime转换为字符串,具有可读格式的日期?
- 美丽的汤和提取div及其内容的ID
- 在Python中重置生成器对象