python,时间字符串,变成utc时间的毫秒级时间戳

from datetime import datetime
date_str = '2022-04-27_10:40'

#date str --> date time
date_time = datetime.strptime(date_str, '%Y-%m-%d_%H:%M')#'%Y-%m-%d %H:%M:%S.%f'
print(date_time)  #2022-04-27 10:40:00

#date time --> utc date time
import pytz
utc_now = date_time.astimezone(pytz.timezone("UTC"))
print(utc_now)  #2022-04-27 02:40:00+00:00

#utc date time -->秒级时间戳
int_time = int(datetime.timestamp(utc_now))
print(int_time) #1651027200 10位数是秒级

#秒级时间戳 --> 毫秒级时间戳
int_time =  int(round(int_time * 1000))
print(int_time) #1651027200000 13位数是毫秒级
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用 C++11 标准库中的 `<chrono>` 头文件来实现时间字符串转换为毫秒时间戳。 具体步骤如下: 1. 将时间字符串解析为 `tm` 结构体,可以使用 `strptime()` 函数,但是这个函数不是标准 C++ 函数,可以使用 Boost 库提供的 `boost::posix_time::time_from_string()` 函数来实现。 2. 将 `tm` 结构体转换为 `std::chrono::time_point` 类型,可以使用 `std::chrono::system_clock::from_time_t()` 函数。 3. 将 `std::chrono::time_point` 类型转换为毫秒时间戳,可以使用 `std::chrono::time_point_cast<std::chrono::milliseconds>()` 函数。 下面是一个示例代码: ```c++ #include <iostream> #include <chrono> #include <boost/date_time/posix_time/posix_time.hpp> int main() { // 时间字符串 std::string time_str = "2022-01-01 00:00:00.123"; // 解析时间字符串为 boost::posix_time::ptime 类型 boost::posix_time::ptime time = boost::posix_time::time_from_string(time_str); // 将 boost::posix_time::ptime 类型转换为 std::chrono::time_point 类型 std::chrono::system_clock::time_point time_point = std::chrono::system_clock::from_time_t(boost::posix_time::to_time_t(time)); // 将 std::chrono::time_point 类型转换为毫秒时间戳 std::chrono::milliseconds timestamp = std::chrono::time_point_cast<std::chrono::milliseconds>(time_point).time_since_epoch(); std::cout << timestamp.count() << std::endl; // 输出毫秒时间戳 return 0; } ``` 输出结果为: ``` 1640976000123 ``` 其中 `1640976000123` 是时间字符串 `"2022-01-01 00:00:00.123"` 对应的毫秒时间戳

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值