在Python中将日期时间转换为Unix时间戳 [英] Convert datetime to unix timestamp in python

查看:298
本文介绍了在Python中将日期时间转换为Unix时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试从UTC时间戳转换为正常日期并添加正确的时区时,我找不到将时间转换回Unix时间戳的方法。

When I try to convert from UTC timestamp to normal date and add the right timezone I can't find the way to convert the time back to Unix timestamp.

我在做什么?

utc_dt = datetime.utcfromtimestamp(self.__modified_time)
from_zone = tz.tzutc()
to_zone = tz.tzlocal()

utc = utc_dt.replace(tzinfo=from_zone)
central = utc.astimezone(to_zone)

中心等于


2015-10 -07 12:45:04 + 02:00

2015-10-07 12:45:04+02:00

这是我在运行代码时所拥有的,我需要转换时间回到时间戳记。

This is what I have when running the code, and I need to convert the time back to timestamp.

推荐答案

from datetime import datetime
from datetime import timedelta
from calendar import timegm

utc_dt = datetime.utcfromtimestamp(self.__modified_time)
from_zone = tz.tzutc()
to_zone = tz.tzlocal()

utc = utc_dt.replace(tzinfo=from_zone)
central = utc.astimezone(to_zone)
unix_time_central = timegm(central.timetuple())

这篇关于在Python中将日期时间转换为Unix时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆