簡體   English   中英

如何獲取Python日期時間的值

[英]How to get the value of Python datetime

我想使用python代碼ex獲得datetime的值。 20141104那是我想要的示例,如何獲取這樣的日期時間。

import calendar
for month in range(1, 13):
    year = 2014
    make_calendar = calendar.monthcalendar(year, month)
    for weekend in make_calendar:
        for day in weekend:
            if (day != 0):
                parameter = str(year) + str(month) + str(day)
                print parameter

->我嘗試獲取例如示例的值,但是結果是201442。我想要20140402而不是201442。

我需要幫助。

user1153551已經顯示了如何使用日歷模塊執行所需的操作,但是您應該考慮使用具有強大功能strftime的datetime模塊。 當您需要在月或年級別上對日歷進行操作和/或設置其格式時,日歷模塊非常有用,但是對於單個日期級別的較低級別的操作,日期時間可能更適合。

例如:

#! /usr/bin/env python

from datetime import date, timedelta

#A timedelta object of 1 day
oneday = timedelta(days=1)

year = 2014

#A date object of the start of the year
current_day = date(year, 1, 1)

#Print all the days of the given year in YYYYmmdd format
while current_day.year == year:
    print current_day.strftime("%Y%m%d")
    current_day += oneday

您可以使用以下代碼來獲得所需的輸出:

     from time import gmtime, strftime,time, sleep
     date = strftime("%Y%m%d")
     print date

例如,使用'%02d' % month來歸檔日期,月份的前導零。

>>> import datetime
>>> '%02d' % datetime.date.today().month
'11'

Python代碼

import calendar
for month in range(1, 13):
    year = 2014
    make_calendar = calendar.monthcalendar(year, month)
    for weekend in make_calendar:
        for day in weekend:
            if (day != 0):
                parameter = '%02d%02d%02d' % (year, month, day)
                print parameter

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM