seodaewon
seodaewon

Reputation: 11

How to get the value of Python datetime

I want to get the value of datetime using python code ex. 20141104 that is example what I want to get then, How can I get the datetime like that.

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

-> I try to get value like example but, the result is 201442. I want to 20140402 not 201442.

I'm in need of help.

Upvotes: 0

Views: 2465

Answers (3)

PM 2Ring
PM 2Ring

Reputation: 55469

user1153551 has shown how to do what you want using the calendar module, but you should consider using the datetime module instead, with its powerful strftime method. The calendar module is great when you need to manipulate and/or format calendar at the month or year level, but for lower level manipulation at the level of individual dates, datetime is probably more suitable.

For example:

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

Upvotes: 2

Jaykumar Patel
Jaykumar Patel

Reputation: 27614

Use '%02d' % month to archive day, month with leading zero for Example,

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

Python Code

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

Upvotes: 0

lessy
lessy

Reputation: 19

You can use following code to get desired output:

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

Upvotes: 1

Related Questions