加入收藏 | 设为首页 | 会员中心 | 我要投稿 我爱制作网_池州站长网 (https://www.0566zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 服务器 > 搭建环境 > Unix > 正文

如何将字符串日期时间转换为 UTC UNIX?

发布时间:2022-11-10 12:48:12 所属栏目:Unix 来源:
导读:  You're setting time zone to UTC when converting to datetime.转换为日期时间时,您将时区设置为 UTC。 But since your input represents time in Germany you want a time zone that is active there.但是
  You're setting time zone to UTC when converting to datetime.转换为日期时间时,您将时区设置为 UTC。 But since your input represents time in Germany you want a time zone that is active there.但是由于您的输入代表德国的时间unix时间戳,您需要一个在那里有效的时区。 EX:前任:
 
  from datetime import datetime
 
  from zoneinfo import ZoneInfo # Python 3.9+, can use backports.zoneinfo for older versions
 
  stime = "202001010000"
 
  # stime represents time in Germany so we use time zone
 
  time_zone = ZoneInfo('Europe/Berlin')
 
  # to datetime, with tz set:
 
  dtobj = datetime.strptime(stime, "%Y%m%d%H%M").replace(tzinfo=time_zone)
 
  # unix time
 
  ts = dtobj.timestamp()
 
  print(ts)
 
  # 1577833200.0
 
  # back to datetime, again specify time zone
 
  dtobj = datetime.fromtimestamp(ts, tz=time_zone)
 
  print(dtobj)
 
  # 2020-01-01 00:00:00+01:00
 
  Note that if the input represents the same time zone your OS is configured to use, this works correctly without setting a time zone.请注意,如果输入代表您的操作系统配置使用的同一时区,则无需设置时区即可正常工作。 But I think it's better to be explicit here, to avoid confusion if you eg run this script on a machine configured to use another time zone.但我认为最好在这里明确一点,以避免在您例如在配置为使用另一个时区的机器上运行此脚本时造成混淆。
 
 

(编辑:我爱制作网_池州站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章