2017-08-22 22 views
-2

所以我要開始/停止每個月的時間戳某一特定年份每月的開始/結束,所以我想出了這個:生成時間戳某一特定年份

#!/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。

謝謝。

+0

讓我明白了。你想要的時間戳,例如,在1996年1月開始的時刻? –

+0

準確的預期結果是什麼? – bam500

+0

1996/01/01 - 00:00:01(first January 1 seond) 1996/02/01 - 00:00:01(first fevuary 1 second),等等 –

回答

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' 
+0

是的,我一直在玩整天的時間戳,所以我完全忘記了datetilme的構造函數:x –

+0

有時生活就是這樣! –

2

爲什麼不只是這樣?

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

哦,天哪,我爲什麼要這樣寫代碼事實上,我可以做到這一點。 :x –

相關問題