在Python中将datetime更改为Unix时间戳

The*_*ong 22 python unix time datetime timestamp

请帮我将datetime对象(例如: 2011-12-17 11:31:00-05:00)(包括时区)更改为Unix时间戳(如Python中的函数time.time()).

Shn*_*nkc 14

另一种方式是:

import calendar
from datetime import datetime
d = datetime.utcnow()
timestamp=calendar.timegm(d.utctimetuple())
Run Code Online (Sandbox Code Playgroud)

时间戳是unix时间戳,它显示与datetime对象d相同的日期.

  • 注意:它会删除几分之一秒.要保留微秒,请使用:[`(d - datetime(1970,1,1)).total_seconds()`](http://stackoverflow.com/a/8778548/4279) (4认同)

use*_*780 12

import time

import datetime

dtime = datetime.datetime.now()

ans_time = time.mktime(dtime.timetuple())
Run Code Online (Sandbox Code Playgroud)

  • 本地时间可能是不明确的,例如,在DST转换结束期间("退回").`timetuple()`将`tm_isdst`设置为`-1`,强制`mktime()`猜测,即有50%的可能性它是错误的.使用utc时间或感知日期时间对象. (2认同)

DS.*_*DS. 6

不完整的答案(不涉及时区),但希望有用:

time.mktime(datetime_object.timetuple())
Run Code Online (Sandbox Code Playgroud)

**根据以下评论编辑**

在我的程序中,用户输入datetime,选择时区....我创建了一个时区列表(使用pytz.all_timezones)并允许用户从该列表中选择一个时区.

Pytz模块提供必要的转换.例如,如果dt是您的datetime对象,并且用户选择了"美国/东方"

import pytz, calendar
tz = pytz.timezone('US/Eastern')
utc_dt = tz.localize(dt, is_dst=True).astimezone(pytz.utc)
print calendar.timegm(utc_dt.timetuple())
Run Code Online (Sandbox Code Playgroud)

该论点is_dst=True是在夏令时结束时间隔1小时内解决模糊时间(请参阅http://pytz.sourceforge.net/#problems-with-localtime).