【发布时间】:2017-08-22 15:54:53
【问题描述】:
所以我想要特定年份每个月的开始/停止时间戳,所以我想出了这个:
#!/usr/bin/env python
# --*-- encoding: utf-8 --*--
import datetime
from dateutil.relativedelta import relativedelta
def convert_datetime_to_timestamp(datetime_object):
return int((datetime_object - datetime.datetime(1970, 1, 1)).total_seconds())
def get_timestamp_one_month_later(timestamp):
start = datetime.datetime.fromtimestamp(float(timestamp))
return convert_datetime_to_timestamp(start + relativedelta(months=+1))
def get_wholeyear_months_start_end(year):
january_1st = convert_datetime_to_timestamp(datetime.datetime.strptime("{}/01/01-00:00:01".format(year), '%Y/%m/%d-%H:%M:%S'))
whole_year_timestamps = [january_1st]
old_timestamp = january_1st
for _ in range(12):
old_timestamp = get_timestamp_one_month_later(old_timestamp)
whole_year_timestamps.append(old_timestamp)
return whole_year_timestamps
print get_wholeyear_months_start_end(1996)
生成这个:
820454401 = 1/1/1996 à 1:00:01
823136401 = 1/2/1996 à 2:00:01
825645601 = 1/3/1996 à 3:00:01
...
852145201 = 1/1/1997 à 20:00:01
正如您所见,每次都有 1 小时的延迟。 我不知道为什么(我猜这与我的语言环境有关,但究竟是什么?)。
我在具有法语语言环境的 Windows 7 上使用 python 2.7。
谢谢。
【问题讨论】:
-
让我明白。例如,您想要 1996 年 1 月开始的那一刻的时间戳?
-
预期的结果究竟是什么?
-
1996/01/01 - 00:00:01(1 月 1 日) 1996/02/01 - 00:00:01(2 月 1 日),以此类推
标签: python python-2.7 date