Python中的时间格式的读取与转换(time模块)

使用time模块可以查看并处理时间和日期相关内容。

一、时间的表示格式

在Python中,表示时间的格式有4种较为常用,分别是浮点数格式、标准可读格式、格式化格式以及自定义格式。(名字是自己起的,非官方命名)

(1)浮点数格式

用一个float格式的浮点数表示时间,其具体含义表示为从世界标准纪元时间(1970年1月1日)起算至该时间节点的秒数。

(2)标准可读格式

形式为——“星期几 月份 日期 时:分:秒 年份”,便于人阅读。

(3)格式化格式(time.struct_time)

分别用多个参数来表示年份、月份以及时分秒等信息,便于计算机进行处理。

(4)自定义格式

根据自己的需求将时间日期信息整理为自定义格式的字符串。

# 浮点数格式
<class 'float'>
1667321639.1330378

# 标准可读格式
<class 'str'>
Wed Nov  2 00:53:59 2022

# 格式化格式
<class 'time.struct_time'>
time.struct_time(tm_year=2022, tm_mon=11, tm_mday=2, tm_hour=0, tm_min=53, tm_sec=59, tm_wday=2, tm_yday=306, tm_isdst=0)

# 自定义格式
<class 'str'>
2022年11月01日 11:59:59

 不同的格式之间的转换关系如下图:

 

二、时间的读取与格式转换

1. 使用time.time()方法读取为浮点数格式

time.time()方法用于读取计算机内部时间,输出为浮点数格式。

import time

t1 = time.time()
print(t1)

Out:
1667322679.7262034

2. 使用time.localtime()和time.gmtime()方法读取为格式化格式

time.localtime()和time.gmtime()方法分别读取当地时间和世界时间,输出为格式化格式。 

import time

t1 = time.localtime()  # 本地时间
t2 = time.gmtime()  # 世界时间
print(t1)
print(t2)

Out:
time.struct_time(tm_year=2022, tm_mon=11, tm_mday=2, tm_hour=1, tm_min=12, tm_sec=58, tm_wday=2, tm_yday=306, tm_isdst=0)
time.struct_time(tm_year=2022, tm_mon=11, tm_mday=1, tm_hour=17, tm_min=12, tm_sec=58, tm_wday=1, tm_yday=305, tm_isdst=0)

3. 使用time.ctime()和time.asctime()方法读取为标准可读格式

当time.ctime()和time.asctime()输入参数为空时,可以直接读取当前时间为标准可读格式。

import time

t1 = time.ctime()
t2 = time.asctime()
print(t1)
print(t2)

Out:
Wed Nov  2 01:10:01 2022
Wed Nov  2 01:10:01 2022

time.ctime()方法可将浮点数格式转换为标准可读格式。

time.asctime()方法可将格式化格式转换为标准可读格式。

import time

t1 = time.ctime(time.time())  # 将浮点数格式转换为标准可读格式
t2 = time.asctime(time.localtime())  # 将格式化格式转换为标准可读格式
print(t1)
print(t2)

Out:
Wed Nov  2 01:01:41 2022
Wed Nov  2 01:01:41 2022

4. 使用time.strftime()和time.strptime()完成与自定义格式的互转

time.strftime()可以将格式化格式转换为自定义格式。

import time

t1 = time.localtime()  # 格式化格式
s1 = time.strftime("%Y-%m-%d %H:%M:%S", t1)
print(s1)

Out:
2022-11-02 01:21:28  # 自定义格式

time.strptime()与time.strftime()相反,可以将自定义格式转换为格式化格式。

import time

s1 = "2022年11月01日 11:59:59"  # 自定义格式
t1 = time.strptime(s1, "%Y年%m月%d日 %H:%M:%S")
print(t1)

Out:
time.struct_time(tm_year=2022, tm_mon=11, tm_mday=1, tm_hour=11, tm_min=59, tm_sec=59, tm_wday=1, tm_yday=305, tm_isdst=-1)

DQN(Deep Q-Network)是一种使用深度神经网络实现的强化学习算法,用于解决离散动作空间的问题。在PyTorch中实现DQN可以分为以下几个步骤: 1. 定义神经网络:使用PyTorch定义一个包含多个全连接层的神经网络,输入为状态空间的维度,输出为动作空间的维度。 ```python import torch.nn as nn import torch.nn.functional as F class QNet(nn.Module): def __init__(self, state_dim, action_dim): super(QNet, self).__init__() self.fc1 = nn.Linear(state_dim, 64) self.fc2 = nn.Linear(64, 64) self.fc3 = nn.Linear(64, action_dim) def forward(self, x): x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return x ``` 2. 定义经验回放缓存:包含多条经验,每条经验包含一个状态、一个动作、一个奖励和下一个状态。 ```python import random class ReplayBuffer(object): def __init__(self, max_size): self.buffer = [] self.max_size = max_size def push(self, state, action, reward, next_state): if len(self.buffer) < self.max_size: self.buffer.append((state, action, reward, next_state)) else: self.buffer.pop(0) self.buffer.append((state, action, reward, next_state)) def sample(self, batch_size): state, action, reward, next_state = zip(*random.sample(self.buffer, batch_size)) return torch.stack(state), torch.tensor(action), torch.tensor(reward), torch.stack(next_state) ``` 3. 定义DQN算法:使用PyTorch定义DQN算法,包含训练和预测两个方法。 ```python class DQN(object): def __init__(self, state_dim, action_dim, gamma, epsilon, lr): self.qnet = QNet(state_dim, action_dim) self.target_qnet = QNet(state_dim, action_dim) self.gamma = gamma self.epsilon = epsilon self.lr = lr self.optimizer = torch.optim.Adam(self.qnet.parameters(), lr=self.lr) self.buffer = ReplayBuffer(100000) self.loss_fn = nn.MSELoss() def act(self, state): if random.random() < self.epsilon: return random.randint(0, action_dim - 1) else: with torch.no_grad(): q_values = self.qnet(state) return q_values.argmax().item() def train(self, batch_size): state, action, reward, next_state = self.buffer.sample(batch_size) q_values = self.qnet(state).gather(1, action.unsqueeze(1)).squeeze(1) target_q_values = self.target_qnet(next_state).max(1)[0].detach() expected_q_values = reward + self.gamma * target_q_values loss = self.loss_fn(q_values, expected_q_values) self.optimizer.zero_grad() loss.backward() self.optimizer.step() def update_target_qnet(self): self.target_qnet.load_state_dict(self.qnet.state_dict()) ``` 4. 训练模型:使用DQN算法进行训练,并更新目标Q网络。 ```python dqn = DQN(state_dim, action_dim, gamma=0.99, epsilon=1.0, lr=0.001) for episode in range(num_episodes): state = env.reset() total_reward = 0 for step in range(max_steps): action = dqn.act(torch.tensor(state, dtype=torch.float32)) next_state, reward, done, _ = env.step(action) dqn.buffer.push(torch.tensor(state, dtype=torch.float32), action, reward, torch.tensor(next_state, dtype=torch.float32)) state = next_state total_reward += reward if len(dqn.buffer.buffer) > batch_size: dqn.train(batch_size) if step % target_update == 0: dqn.update_target_qnet() if done: break dqn.epsilon = max(0.01, dqn.epsilon * 0.995) ``` 5. 测试模型:使用训练好的模型进行测试。 ```python total_reward = 0 state = env.reset() while True: action = dqn.act(torch.tensor(state, dtype=torch.float32)) next_state, reward, done, _ = env.step(action) state = next_state total_reward += reward if done: break print("Total reward: {}".format(total_reward)) ``` 以上就是在PyTorch中实现DQN强化学习的基本步骤。需要注意的是,DQN算法中还有很多细节和超参数需要调整,具体实现过程需要根据具体问题进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值