【问题标题】:Generating timestamp for each month start/end for a specific year为特定年份的每个月开始/结束生成时间戳
【发布时间】: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


【解决方案1】:
>>> from datetime import datetime
>>> for mois in range(1,13):
...     d = datetime(1996, mois, 1, 0, 0, 1)
...     '%s = %s' % (int(d.timestamp()), d.strftime('%Y/%m/%d à %H:%M:%S'))
...     
'820472401 = 1996/01/01 à 00:00:01'
'823150801 = 1996/02/01 à 00:00:01'
'825656401 = 1996/03/01 à 00:00:01'
'828331201 = 1996/04/01 à 00:00:01'
'830923201 = 1996/05/01 à 00:00:01'
'833601601 = 1996/06/01 à 00:00:01'
'836193601 = 1996/07/01 à 00:00:01'
'838872001 = 1996/08/01 à 00:00:01'
'841550401 = 1996/09/01 à 00:00:01'
'844142401 = 1996/10/01 à 00:00:01'
'846820801 = 1996/11/01 à 00:00:01'
'849416401 = 1996/12/01 à 00:00:01'

【讨论】:

  • 是的,我整天都在玩时间戳,所以我完全忘记了 datetilme 构造函数:x
  • 有时候生活就是这样!
【解决方案2】:

为什么不只是这样?

for i in range(1,13):
    print (datetime.datetime(1996, i, 1) - datetime.datetime(1970, 1, 1)).total_seconds()

【讨论】:

  • 天哪,我为什么要编写这么复杂的代码,我确实可以做到。 :x
猜你喜欢
  • 2021-11-16
  • 2011-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多