简体   繁体   English

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

[英]Change datetime to Unix time stamp in Python

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

Another way is: 另一种方式是:

import calendar
from datetime import datetime
d = datetime.utcnow()
timestamp=calendar.timegm(d.utctimetuple())

Timestamp is the unix timestamp which shows the same date with datetime object d. 时间戳是unix时间戳,它显示与datetime对象d相同的日期。

import time

import datetime

dtime = datetime.datetime.now()

ans_time = time.mktime(dtime.timetuple())

Incomplete answer (doesn't deal with timezones), but hopefully useful: 不完整的答案(不涉及时区),但希望有用:

time.mktime(datetime_object.timetuple())

** Edited based on the following comment ** **根据以下评论编辑**

In my program, user enter datetime, select timezone. 在我的程序中,用户输入datetime,选择时区。 ... I created a timezone list (use pytz.all_timezones) and allow user to chose one timezone from that list. ...我创建了一个时区列表(使用pytz.all_timezones)并允许用户从该列表中选择一个时区。

Pytz module provides the necessary conversions. Pytz模块提供必要的转换。 Eg if dt is your datetime object, and user selected 'US/Eastern' 例如,如果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())

The argument is_dst=True is to resolve ambiguous times during the 1-hour intervals at the end of daylight savings (see here http://pytz.sourceforge.net/#problems-with-localtime ). 参数is_dst=True用于解决夏令时结束时1小时间隔内的模糊时间(请参阅此处http://pytz.sourceforge.net/#problems-with-localtime )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM