def calendar_():
  cal = calendar.month(2017, 6)  # by default w=2 l=1
  print cal  # 2017年6月份日历

  print '--------------------'
  # calendar内置函数
  #calendar of year 2017: c=distance(month); l=line(week); w=distance(day)
  print calendar.calendar(2017, w=2, l=1, c=6)  #lenth(line)= 21* W+18+2* C

  print calendar.firstweekday() # start weekday, 0 by default, i.e. Monday
  # calendar.setfirstweekday(weekday)  # 0(Monday) to 6(Sunday)

  print calendar.isleap(2017) # return True or False
  print calendar.leapdays(2000, 2016) # number of leap years between year 1 and year 2

  print calendar.month(2017, 6)
  print calendar.monthcalendar(2017, 6)

  print calendar.monthrange(2017, 6)  # return (a, b)  a=starting weekday b=days in month

  calendar.prcal(2017, w=2, l=1, c=4)  # equals to print calendar.calendar(2017, w=2, l=1, c=4)
  calendar.prmonth(2017, 6) # equals to print calendar.month(2017, 6)

  print calendar.timegm(time.localtime()) #和time.gmtime相反:接受一个时间元组形式,返回该时刻的时间辍

  print calendar.weekday(2017, 6, 30) # calendar.weekday(year,month,day) return date code
Example #2
0
def minus_month(month, year, cal_window):
	cal_window.erase()
	if (month-1) == 0:
		month = 12
		year -= 1
		cal_window.addstr(0,0,calendar.month(year,month))
	else:
		cal_window.addstr(0,0,calendar.month(year,month-1))
		month -= 1
	cursor_nav(cal_window)
	return month, year
Example #3
0
def plus_month(month, year, cal_window):
	cal_window.erase()
	if (month+1) == 13:
		month = 01
		year += 1
		cal_window.addstr(0,0,calendar.month(year,month))
	else:
		cal_window.addstr(0,0,calendar.month(year,(month+1)))
		month += 1	
	cursor_nav(cal_window)
	return month, year
Example #4
0
def two_months_calendar():
    t = time.localtime()
    cal = calendar.month(t.tm_year, t.tm_mon)

    # set a cursor '##' to point to today
    today = t.tm_mday
    mark = '#' * len(str(today))
    cal = re.sub(r'([\n ])(' + str(today) + ')([\n ])', 
           '\g<1>' + mark + '\g<3>', cal)

    if t.tm_mon == 12:
        cal += calendar.month(t.tm_year + 1, 1)
    else:
        cal += calendar.month(t.tm_year, t.tm_mon + 1)
    return '[cmd]' + cal.replace(" ", "_") + '[/cmd]'
Example #5
0
def prob2():

  import datetime, calendar

  instring = requestString("Please enter your birthday (in format 1776-07-04)") 
  hold = instring.split("-")
 
  calendar.setfirstweekday(6) #make calendar Sun->Sat
  calMonth = calendar.month(int(hold[0]), int(hold[1])) #hold[0] is year, hold[1] is month
  printNow(" ")
  printNow(calMonth)

  today = datetime.date.today()
  holdtheyear = today.strftime("%Y")  #save off this year string
  
  #today
  t_day = datetime.datetime(int(holdtheyear), int(today.strftime("%m")), int(today.strftime("%d")))
  
  # next birthday
  nb_day = datetime.datetime(int(holdtheyear), int(hold[1]), int(hold[2]))
  
  diff = nb_day - t_day
  printNow("Just %i days until your next birthday!" % diff.days)
  
  #days of week from Mon-Sun
  dow = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
  
  hold4th = datetime.datetime(1776, 7, 4).weekday()  
  printNow("\nThe 4th of July, 1776 was a %s." % dow[hold4th])
def main2():
#time
	#函数time.time()用于获取当前时间戳,最适于做日期计算,1970-2038
	import time;
	ticks = time.time()
	print '当前时间戳为:',ticks
#时间元祖:用一个元件装起来的9组数字处理时间
#获取当前时间:从返回浮点数的时间缀方式向时间元祖转换。localtime
	print'----------------------'
	import time
	localtime = time.localtime(time.time())
	print '本地时间为:',localtime
# 获取格式化的时间,asctime()
	print '--------------------'
	import time
	localtime = time.asctime(time.localtime(time.time()))
	print '本地时间为:',localtime
#格式化日期:time-strftime
	print'-----------------------'
	import time
	#格式化成2017-07-25 21:14:19形式
	print time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
	#格式化成Tue Jul 25 21:14:19 2017形式
	print time.strftime('%a %b %d %H:%M:%S %Y',time.localtime())
	#将时间字符串转换为时间戳
	a = 'Tue Jul 25 21:08:49 2017'
	print time.mktime(time.strptime(a,'%a %b %d %H:%M:%S %Y'))
#calendar处理年历和月历
	import calendar
	cal = calendar.month(2017,7)
	print '以下输出2017年7月份的日历:'
	print cal;
Example #7
0
 def __repr__(self):
     ls = [" %s" % l for l in cal.month(self.year, self.month).split('\n')]
     ls = ls[:-1]
     for i in xrange(len(ls)):
         while len(ls[i]) < 22:
             ls[i] += ' '
         if i == 0:
             ls[i] = "%s%s" % (fmt.fb('black', 'green'), ls[i])
         elif i == 1:
             ls[i] = "%s%s" % (fmt.fb('blue', 'cyan'), ls[i])
         if i < 2:
             continue
         ls[i] = "%s%s" % (fmt.bf('blue', 'white'), ls[i])
         su = ls[i][-3:][:2]
         if len(self.hl) > 0 and self.hl[0].year == self.year and \
            self.hl[0].month == self.month:
             for day in self.hl:
                 dstr = ' %s ' % day.strftime("%e")
                 # Replace with 1 more char than necessary so we can
                 # identify continous matches
                 dhls = "<%s> " % dstr[1:-1]
                 ls[i] = ls[i].replace(dstr, dhls)
             ls[i] = ls[i].replace("><", " ")
             ls[i] = ls[i].replace("<", "%s<" % fmt.bf('red', 'reset'))
             ls[i] = ls[i].replace("> ", ">%s" % fmt.bf('blue', 'white'))
             # Highlighted Sundays are bright/bold
             ls[i] = ls[i].replace("%s>" % su, "%s%s%s>" % \
                                   (fmt.bfs('red', 'reset', 'bright'),
                                   su, fmt.s('normal')))
         # Sundays are magenta and bright/bold
         ls[i] = ("%s%s%s " % \
                  (fmt.fs('magenta', 'bright'), su,
                   fmt.fs('white',
                          'normal'))).join(ls[i].rsplit("%s " % su, 1))
     return "%s%s" % (('%s\n' % fmt.r).join(ls), fmt.r)
Example #8
0
    def __init__(self):
        super().__init__()
        class CalendarDay(QtGui.QLabel): pass
        class CalendarFiller(CalendarDay): pass
        class CalendarWeekNumber(CalendarDay): pass

        firstweek = datetime.date(2013,1,1).isocalendar()[1]

        days = [[''.join(y).strip() for y in zip(row[::3], row[1::3])]
                    for row in calendar.month(2013,1).splitlines()[2:]]
        if len(days[-1]) < 7:
            days[-1].extend(['']*(7-len(days[-1])))
        if len(days) < 6:
            days.append(['']*7)
        days = [[str(weeknum)] + week for weeknum, week in zip(range(firstweek, firstweek+6), days)]

        layout = QtGui.QGridLayout(self)
        kill_theming(layout)

        item = []

        for y in range(6):
            item.append([])
            for x in range(8):
                if x == 0:
                    widget = CalendarWeekNumber
                elif days[y][x] == '':
                    widget = CalendarFiller
                else:
                    widget = CalendarDay
                item[y].append(widget(days[y][x]))
                layout.addWidget(item[y][x], y, x)
Example #9
0
def three_month( year, month ):
    """Print three months side-by-side.

    :param year: year
    :param month: middle month to display
    """
    cal_seq= []
    for i in -1, 0, 1:
        ym = (year*12 + month-1) + i
        cal_year, cal_mon = divmod( ym, 12 )
        cal_seq.append( calendar.month( cal_year, cal_mon+1 ).splitlines() )
    # Longest month
    size = max( map( len, cal_seq ) )
    # Examine each month week-by-week
    for i in range(size):
        try:
            col_0= cal_seq[0][i]
        except IndexError:
            col_0= ''
        try:
            col_1= cal_seq[1][i]
        except IndexError:
            col_1= ''
        try:
            col_2= cal_seq[2][i]
        except IndexError:
            col_2= ''
        print( "{0:21s}      {1:21s}      {2:21s}".format(col_0, col_1, col_2) )
    print( "{0:21s}      {1:21s}      {2:21s}".format("LAST MONTH", "THIS MONTH", "NEXT MONTH") )
def homework2():
	import time
	#时间戳
	ticks=time.time()
	print "当前时间戳为:", ticks

	#当前时间
	localtime=time.localtime(time.time())
	print '当前时间为:',localtime

	#格式化时间
	localtime=time.asctime(time.localtime(time.time()))#local前忘+time   套几次就有几次time
	print '当前时间为:',localtime

	#格式化成特定形式strftime
	# 1)格式化成2016-03-20 11:45:39形式
	print time.strftime('%Y-%m-%d %H:%M:%S ',time.localtime())   #%在数字前   忘了加''   localtime后忘加()

	# 格式化成Sat Mar 28 22:24:24 2016形式
	print time.strftime('%a %b %d %H:%M:%S %Y',time.localtime())
	print time.strftime('%A %B %d %H:%M:%S %Y',time.localtime())
	# %a 本地简化星期名称   %A 本地完整星期名称——英文全称    
	#  %b 本地简化的月份名称  %B 本地完整的月份名称

	# 将格式字符串转换为时间戳
	a='2017-06-20 14:03:41'
	print time.mktime(time.strptime(a,'%Y-%m-%d %H:%M:%S'))   #mktime前有time.   是strpt  是p不是f
	#两个是相反的,strftime是将时间格式化,而strptime是转为时间戳  
	 #mktime表示转回时间戳

	#获取某月日历
	import calendar
	cal=calendar.month(2017,6) #后面缺了month  没有year的语法
	print  '下面输出2017年6月的日历'
	print cal
Example #11
0
	def disp_calendar(self):
		# Fill the screen with black
		self.screen.fill( (0,0,0) )
		xmin = 10
		xmax = self.xmax
		ymax = self.ymax
		lines = 5
		lc = (255,255,255) 
		sfn = "freemono"
		fn = "freesans"

		# Draw Screen Border
		pygame.draw.line( self.screen, lc, (xmin,0),(xmax,0), lines )
		pygame.draw.line( self.screen, lc, (xmin,0),(xmin,ymax), lines )
		pygame.draw.line( self.screen, lc, (xmin,ymax),(xmax,ymax), lines )
		pygame.draw.line( self.screen, lc, (xmax,0),(xmax,ymax), lines )
		pygame.draw.line( self.screen, lc, (xmin,ymax*0.15),(xmax,ymax*0.15), lines )

		# Time & Date
		th = self.tmdateTh
		sh = self.tmdateSmTh
		font = pygame.font.SysFont( fn, int(ymax*th), bold=1 )		# Regular Font
		sfont = pygame.font.SysFont( fn, int(ymax*sh), bold=1 )		# Small Font for Seconds

		tm1 = time.strftime( "%a, %b %d   %I:%M", time.localtime() )	# 1st part
		tm2 = time.strftime( "%S", time.localtime() )			# 2nd
		tm3 = time.strftime( " %P", time.localtime() )			# 

		rtm1 = font.render( tm1, True, lc )
		(tx1,ty1) = rtm1.get_size()
		rtm2 = sfont.render( tm2, True, lc )
		(tx2,ty2) = rtm2.get_size()
		rtm3 = font.render( tm3, True, lc )
		(tx3,ty3) = rtm3.get_size()

		tp = xmax / 2 - (tx1 + tx2 + tx3) / 2
		self.screen.blit( rtm1, (tp,self.tmdateYPos) )
		self.screen.blit( rtm2, (tp+tx1+3,self.tmdateYPosSm) )
		self.screen.blit( rtm3, (tp+tx1+tx2,self.tmdateYPos) )

		# Conditions
		ys = 0.20		# Yaxis Start Pos
		xs = 0.20		# Xaxis Start Pos
		gp = 0.075	# Line Spacing Gap
		th = 0.05		# Text Height

		cfont = pygame.font.SysFont( sfn, int(ymax*sh), bold=1 )
		#cal = calendar.TextCalendar()
		yr = int( time.strftime( "%Y", time.localtime() ) )	# Get Year
		mn = int( time.strftime( "%m", time.localtime() ) )	# Get Month
		cal = calendar.month( yr, mn ).splitlines()
		i = 0
		for cal_line in cal:
			txt = cfont.render( cal_line, True, lc )
			self.screen.blit( txt, (xmax*xs,ymax*(ys+gp*i)) )
			i = i + 1

		# Update the display
		pygame.display.update()
Example #12
0
def nextWork():
    import time;
    import calendar;
    
    localtime = time.asctime(time.localtime(time.time()))
    cal = calendar.month(2016, 03)
    
    print "Local current time is: ", localtime
    print cal
def main():
  ticks=time.time()
  print ticks
  localtime=time.asctime(time.localtime(time.time()))
  print localtime
  print time.strftime("%Y-%m-%d%H:%M:%S",time.localtime())
  import calendar
  cal=calendar.month(2017,6)
  print cal
  print calendar.isleap(2017)
Example #14
0
def calendiar():
	global tm
	calend = calendar.month(int(tm[0]),int(tm[1]),2,1)
	calend = calend.split(" ")
	calend = calend[len(calend) - 1]
	b = findnumber(calend)
	calend = calend[b:b+2]
	calend = int(calend)
	if calend == 27:
		calend = 28
	return calend
Example #15
0
	def disp_calendar(self):
		# Fill the screen with black
		self.screen.fill( (0,0,0) )
		xmax = 656 - 35
		ymax = 416 - 5
		lines = 5
		lc = (255,255,255) 
		sfn = "freemono"
		fn = "freesans"

		# Draw Screen Border
		pygame.draw.line( self.screen, lc, (0,0),(xmax,0), lines )
		pygame.draw.line( self.screen, lc, (0,0),(0,ymax), lines )
		pygame.draw.line( self.screen, lc, (0,ymax),(xmax,ymax), lines )
		pygame.draw.line( self.screen, lc, (xmax,0),(xmax,ymax), lines )
		pygame.draw.line( self.screen, lc, (0,ymax*0.15),(xmax,ymax*0.15), lines )

		# Time & Date
		font = pygame.font.SysFont( fn, int(ymax*0.125), bold=1 )		# Regular Font
		sfont = pygame.font.SysFont( sfn, int(ymax*0.075), bold=1 )		# Small Font for Seconds

		tm1 = time.strftime( "%a, %b %d   %I:%M", time.localtime() )	# 1st part
		tm2 = time.strftime( "%S", time.localtime() )					# 2nd
		tm3 = time.strftime( " %P", time.localtime() )					# 

		rtm1 = font.render( tm1, True, lc )
		(tx1,ty1) = rtm1.get_size()
		rtm2 = sfont.render( tm2, True, lc )
		(tx2,ty2) = rtm2.get_size()
		rtm3 = font.render( tm3, True, lc )
		(tx3,ty3) = rtm3.get_size()

		tp = xmax / 2 - (tx1 + tx2 + tx3) / 2
		self.screen.blit( rtm1, (tp,1) )
		self.screen.blit( rtm2, (tp+tx1+3,8) )
		self.screen.blit( rtm3, (tp+tx1+tx2,1) )

		# Conditions
		ys = 0.20		# Yaxis Start Pos
		xs = 0.20		# Xaxis Start Pos
		gp = 0.075	# Line Spacing Gap
		th = 0.06		# Text Height

		#cal = calendar.TextCalendar()
		cal = calendar.month( 2013, 8 ).splitlines()
		i = 0
		for cal_line in cal:
			txt = sfont.render( cal_line, True, lc )
			self.screen.blit( txt, (xmax*xs,ymax*(ys+gp*i)) )
			i = i + 1

		# Update the display
		pygame.display.update()
Example #16
0
    def __init__(self,master):

        #container
        container = Label(master, bg = '#CFCECF')
        container.config(height = 8, width = 25)
        container.pack()
        container.place(x = 595, y = 430)

        #calendar
        cal_x = calendar.month(2016, 4, w = 2, l = 1)
        cal_out = Label(master, text = cal_x, font=('courier', 12, 'bold'), bg='#ffffff')
        cal_out.pack(padx = 3, pady = 10)
        cal_out.place(x = 635, y = 440)
Example #17
0
def timeDemo():
    ticks = time.time()
    print "Number of ticks since 12:00am, January 1, 1970:", ticks

    localtime = time.localtime(time.time())
    print "Local current time :", localtime

    localtime = time.asctime(time.localtime(time.time()))
    print "Local current time :", localtime

    cal = calendar.month(2008, 1)
    print "Here is the calendar:"
    print cal
Example #18
0
def add_gigasecond(year, month,day):

    Fyear=year+31
    Fmonth=month+8 #taking simple 30 day months
    Fday=day+19+month(Fmonth,year)

    while(Fday>30):
        Fmonth+=1
        Fmonth-=30

    if(Fmonth>12):
        Fmonth=Fmonth-12
        Fyear+=1

    return  Fyear, Fmonth,Fday
def main():
	ticks=time.time()

	print "当前时间戳为:", ticks

	localtime=time.asctime(time.localtime(time.time()))
	print "localtime=", localtime

	print time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
	a = "Sat Mar 28 22:24:24 2016"
	print time.mktime(time.strptime(a,"%a %b %d %H:%M:%S %Y"))	
	cal=calendar.month(2017,7)
	print "日历"
	print cal
	print calendar.calendar(2015,w=2,l=1,c=6)
def calendar():

	import calendar#引入calender

	#获取某月日历
	cal=calendar.month(2017,1)
	print '以下输出2017年1月的日历 '
	print cal

	#判断是否为闰年
	print calendar.isleap(2016)
	print calendar.isleap(2017)

	#获取某年日历
	print calendar.calendar(2017,w=2,l=1,c=6)
Example #21
0
def printCal( year, month ) :
	'''four-digit year
month, indexed at 1 (January is 1)
'''

		# start on Sunday, rather than the default Monday
	calendar.setfirstweekday( 6 )
	m = calendar.month( int(year), int(month) )

	weeks = m.splitlines()

		# rip off the month/year string
	title = weeks.pop( 0 ).strip()

		# break each string into a list of tokens
	for i in range( len( weeks )) :
		weeks[i] = weeks[i].split()
	
		# The first and last weeks need to be padded
	for i in range( DAYS_PER_WEEK - len( weeks[1] )) :
		weeks[1].insert( 0, '&nbsp;' )
	
	last = len( weeks ) - 1
	for i in range( DAYS_PER_WEEK - len( weeks[last] )) :
		weeks[last].append( '&nbsp;' )

	print '<table border="%s" cellspacing="%s" width="400">\n\t<tr>' % \
			( BORDER, CELLSPACING )
	print '\t\t<th colspan="%s" bgcolor="#ffff00">%s</th>' % \
		( DAYS_PER_WEEK, title )
	print '\t</tr>\n\t<tr>'
	for day in weeks[0] :
		print '\t\t<th width="14%%">%s</th>' % day
	print '\t</tr>'
	
	weeks.pop( 0 )

	for week in weeks :
		print '\t<tr>'
		for day in week :
			if day.isdigit() and int( day )%3 == 0 :
				print '\t\t<td bgcolor="%s"><center>%s</center></td>' % \
					( BG_COLOR, day )
			else :
				print '\t\t<td><center>%s</center></td>' % day
		print '\t</tr>'

	print '</table>'
def get_calendar():
    import time
    import calendar

    localtime = time.localtime(time.time())
    calendar.setfirstweekday(calendar.MONDAY)
    cal = calendar.month(localtime[0], localtime[1])

    parts = cal.split('\n')
    del parts[0]
    del parts[-1]
    parts[0] = '${{color9}}{}${{color1}}'.format(parts[0])
    cal = '${color1}${offset 175}' + '\n${offset 175}'.join(parts)
    today = '${{color4}}{}${{color1}}'.format(localtime[2])
    new_cal = cal.replace(str(localtime[2]), today)
    print(new_cal)
Example #23
0
	def update(self):
		calendar.setfirstweekday(int(self.config['first_day_of_week']))
		now = datetime.date.today()

		if ((now.month+self._month_offset)>12):
			self._month_offset=1-now.month
			self._year_offset+=1
		if ((now.month+self._month_offset)<1):
			self._month_offset=12-now.month
			self._year_offset-=1

		year = now.year+self._year_offset
		month =  now.month+self._month_offset
		print year, month
		print self._year_offset, self._month_offset

		self._cal = self.__buildcal(calendar.month(year, month))
Example #24
0
 def _get_current_time(self):
   year, month, date, hour, minute, sec, dow = time.localtime(time.time())[:7]
   calendar.setfirstweekday(calendar.SUNDAY)
   cal = calendar.month(year, month).split('\n')[2:]
   wom = 0
   for week in cal:
     for day in week.split():
       if int(day) == int(date):
         wom = cal.index(week) + 1
   return {           'date': date, 
               'day_of_week': dow, 
                      'time': '%02d:%02d' % (hour, minute),
                    'minute': minute,
                      'hour': hour,
                     'ftime': '%02d:%02d' % (hour, minute/5*5),
             'week_of_month': wom
            }
def load_cal(date):

    obj = w.Text1
    w.date = date
    calendar.setfirstweekday(calendar.SUNDAY)
    cal_str = calendar.month(date.year, date.month)
    obj.delete(1.0,END)
    obj.insert(END,cal_str)
    if date.year == w.today.year and date.month == w.today.month:
        # Color today's day if month and year are current month and year.
        day = str(date.day)
        obj.tag_configure('e0', foreground='red')
        obj.tag_remove('e0', 1.0, END)
        start = cal_str.find(day,15)  # Skip month and year
        end = start + len(day)
        min_c = '%d.0+%dchars' % (1, start)
        max_c = '%d.0+%dchars' % (1, end)
        obj.tag_add('e0', min_c, max_c)
Example #26
0
def update(y, m, tx, curdate):  # generate calendar with right colors
    calstr = calendar.month(y, m)
    tx.configure(state=Tkinter.NORMAL)
    tx.delete("0.0", Tkinter.END)  # remove previous calendar
    tx.insert(Tkinter.INSERT, calstr)
    for i in range(2, 9):
        tx.tag_add("others", "{}.0".format(i), "{}.end".format(i))  # tag days for coloring
        if len(tx.get("{}.0".format(i), "{}.end".format(i))) == 20:
            tx.tag_add("sun", "{}.end-2c".format(i), "{}.end".format(i))
    tx.tag_config("sun", foreground="#fb4622")
    tx.tag_config("others", foreground="#427eb5")
    tx.tag_add("head", "1.0", "1.end")
    if curdate[0] == y and curdate[1] == m:
        index = tx.search(str(curdate[2]), "2.0")  # search for today's date
        tx.tag_add("cur", index, "{}+2c".format(index))  # highlight today's date
        tx.tag_config("cur", background="blue", foreground="white")
    tx.tag_config("head", font=segoe, foreground="#0d8241", justify=Tkinter.CENTER)
    tx.configure(state=Tkinter.DISABLED)  # make text view not editable
 def render(self):
     calendar.setfirstweekday(6)
     lines = calendar.month(self.year, self.month).splitlines()
     s = []
     s.append('<table cellpadding="3" cellspacing="1" class="calendar">')
     mon, year = lines[0].strip().split()
     s.append('<caption><strong>%(mon)s %(year)s</strong></caption>' % {'mon':_(mon), 'year':year})
     s.append('<thead><tr class="wkhead">')
     for i in ('Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'):
         s.append('<th class="wkhead_item">%(wkhead)s</th>' % {'wkhead':_(i)})
     s.append('</tr></thead>')
     s.append('<tbody>')
     for line in lines[2:]:
         s.append('<tr class="wkbody">')
         v = [line[i:i+2]  for i in range(0, len(line.rstrip()), 3)]
         for i, day in enumerate(v):
             t, text = self.on_days(day, self.sepcial_days)
             s.append('<td class="%s">%s</td>' % (t, text))
         while i < 6:
             t, text = self.on_days('  ', self.sepcial_days)
             s.append('<td class="%s">%s</td>' % (t, text))
             i += 1
         s.append('</tr>')
     
     if self.month == 1:
         prev_mon = self.get_date_url(self.year - 1 , 12)
     else:
         prev_mon = self.get_date_url(self.year, self.month - 1)
     if self.month == 12:
         next_mon = self.get_date_url(self.year + 1, 1)
     else:
         next_mon = self.get_date_url(self.year, self.month + 1)
     s.append('<tr class="wknav"><td class="wkday_none"><a href="%(prev_year)s" title="Prev Year">&lt;&lt;</a></td>'
         '<td class="wkday_none"><a href="%(prev_mon)s" title="Prev Month">&lt;</a></td><td></td><td></td><td></td>'
         '<td class="wkday_none"><a href="%(next_mon)s" title="Next Month">&gt;</a></td>'
         '<td class="wkday_none"><a href="%(next_year)s" title="Next Year">&gt;&gt;</a></td></tr>' % 
         {'prev_year':self.get_date_url(self.year-1, self.month), 
         'prev_mon':prev_mon,
         'next_mon':next_mon, 
         'next_year':self.get_date_url(self.year + 1, self.month)})
     s.append('</tbody></table>')
     
     return ''.join(s)
def calendarText():
    """example return:

             January 2016
     Mo Tu We Th Fr Sa Su
                  1  2  3
      4  5  6  7  8  9 10
     11 12 13 14 15 16 17
     18 19 20 21 22 23 24
     25 26 27 28 29 30 31
     """

    now = datetime.datetime.now()
    x = "%d" % now.year
    y = "%d" % now.month

    yy = int(x)
    mm = int(y)
    return calendar.month(yy, mm)
def main():
	ticks=time.time()
	print ' 当前的时间戳: ',ticks

	localtime = time.localtime(ticks)
	print "本地时间为 :", localtime

	localtime1 = time.asctime(localtime)
	print "本地时间为 :", localtime1

	print time.strftime("%Y-%m-%d %H:%M:%S",localtime) 
	print time.strftime("%a %b %d %H:%M:%S %Y",localtime) 

	a = "Sat Mar 28 22:24:24 2016"
	print time.mktime(time.strptime(a,"%a %b %d %H:%M:%S %Y"))

	cal = calendar.month(2017, 5)
	print "以下输出2017年5月份的日历:"
	print cal;
Example #30
0
def parse_out_weeks(year, stats):

	# Defaults and lists to return
	week_count = 1

	# Loop all 12 months
	for month in range(1, 13):

		# Get the mondays for that month
		mondays = [ day.split()[0] for day in calendar.month(year, month).split("\n")[2:-1] if not day.startswith("  ")]

		# Loop each monday and check for search in that week.
		for monday in mondays:

			# Contruct info object
			week_obj = {}
			week_obj['date'] = "%i-%02i-%02i" % (year, int(month), int(monday))

			# Defaults. All 0 naturally
			week_obj["total"] = 0
			week_obj["found"] = 0
			week_obj["failure"] = 0
			week_obj["notfound"] = 0

			# Loop the stats and find the weekly searches
			for stat in stats:

				# Check if the week matches
				if stat.week == week_count and int(stat.total) > 0:

					# if the week matches add the amounts
					week_obj['total'] += int(stat.total)
					week_obj['found'] += int(stat.found)
					week_obj['failure'] += int(stat.failed)
					week_obj['notfound'] += int(stat.notfound)

			# Increment the count of week we are one.
			week_count += 1

			# Was thinking of only adding weeks bigger than 0 but this is the DAL
			# Want to keep logic like that to the upper level.
			yield week_obj
Example #31
0
import calendar
from datetime import datetime, timedelta

future = datetime.now() + timedelta(weeks=300)

print(calendar.month(future.year, future.month))
Example #32
0
def print_calendar(month=today.month, year=today.year):
    this_calendar = calendar.month(year, month)
    print(this_calendar)
Example #33
0
import time

print(time.time())

print(dir(time))
print(time.localtime())
print(time.gmtime())
print(time.time_ns())
# print(time.clock())
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

import calendar

cal = calendar.month(2019, 4)
print("以下输出2016年1月份的日历:")

print(cal)
import calendar

print(calendar.isleap(2019))
print(calendar.month(2020, 10))
print(calendar.calendar(2020))
Example #35
0
# encoding: utf-8
'''
@author: zzj
@license: (C) Copyright 2008-2030
@contact: [email protected]
@software: python
@file: calendar.py
@time: 2018/7/4 16:56
@desc:
'''
import calendar
# calendar.setfirstweekday()

# print(calendar.firstweekday())
print(calendar.month(2018, 3, w=2, l=1))

# print(calendar.calendar(2018,w=1,l=1,c=6))
Example #36
0
# calendar 获取一年的日历字符串
# calendar(w,l,c) w = 每个日期之间的间隔字符数 , l = 每周所占用的行数 c = 每个月之间的间隔字符数
print(calendar.calendar(2018))  # 打印2018的日历
print(type(calendar.calendar(2018)))  # 查看打印出来的东西是什么类型

# 使用参数改变日历
print(calendar.calendar(2017, l=0, c=5))

# isleap 判断某一年是否为闰年
print(calendar.isleap(2000))

# leapdays:获取指定年份之间的闰年的个数
print(calendar.leapdays(2000, 2004))  # 算左不算右

# month:获取某个月的日历字符串
print(calendar.month(2018, 12))  # 第一个参数为年,第二个参数为月

# monthrange:获取某个月是以周几开始和天数
# 其返回的值是元祖(周几开始,天数
k, v = calendar.monthrange(2018, 11)
print(k, " ", v)

# monthcalendar :将某个月的每个星期以长方形列表的方式返回
# 返回类型为: 二级列表
# 注意:矩形中没有的天数和第一天用0表示
m = calendar.monthcalendar(2018, 11)
print(m)
print(type(m))

# prcal 不需要print直接打印日历
# 无返回值
Example #37
0
# using isleap() to check if year is leap or not
if (calendar.isleap(2008)):
    print("The year is leap")
else:
    print("The year is not leap")

# using leapdays() to print leap days between years
print("The leap days between 1950 and 2000 are : ")
print(calendar.leapdays(1950, 2000))

# Python code to demonstrate the working of
# month()

# using month() to display month of specific year
print("The month 5th of 2016 is : ")
print(calendar.month(2016, 5, 2, 1))

# Python code to demonstrate the working of
# monthrange() and prcal()
# using monthrange() to print start week day and
# number of month
print("The start week number and no. of days of month : ")
print(calendar.monthrange(2008, 2))

# using prcal() to print calendar of 1997
print("The calendar of 1997 is : ")
calendar.prcal(1997, 2, 1, 5)

# Python code to demonstrate the working of
# prmonth() and setfirstweekday()
Example #38
0
import calendar

cal = calendar.month(2020, 12)

print(cal)
Example #39
0
   Then exit the program.

Note: the user should provide argument input (in the initial call to run the file) and not 
prompted input. Also, the brackets around year are to denote that the argument is
optional, as this is a common convention in documentation.

This would mean that from the command line you would call `python3 14_cal.py 4 2015` to 
print out a calendar for April in 2015, but if you omit either the year or both values, 
it should use today’s date to get the month and year.
"""

from datetime import datetime
import calendar
import sys
# Get the argument
args = sys.argv

if len(sys.argv) == 3:
    month = sys.argv[1]
    year = sys.argv[2]
elif len(sys.argv) == 2:
    month = sys.argv[1]
    year = str(datetime.today())[0:4]
elif len(sys.argv) == 1:
    month = str(datetime.today())[5:7]
    year = str(datetime.today())[0:4]
else:
    print('Please run command with this format 14_cal.py month [year]')

print(calendar.month(int(year), int(month)))
import calendar

cal = calendar.month(2008, 1)

print "Here is the calendar:"
print cal

cal = calendar.month(2013, 11)

print "Here is the calendar:"
print cal
Example #41
0
print(cmath.sin(45))
print(random.randint(0, 9))
a = 1
b = 2
a, b = b, a
c = 1234
print(c**b + 1 / b + a)
print(max((a, b, c)))
print(func.reduce(lambda x, y: x * y, range(1, 8)))
print('以下是99乘法表')
for i in range(1, 10):
    for j in range(1, i + 1):
        print('{}*{}={}\t'.format(i, j, i * j), end=' ')
    print('')
print('下面是一个日历')
print(calendar.month(2017, 3))
## python3 正则表达式
print(re.match(r'www', 'www.dugu.com').span())
print(re.match(r'com', 'www.dugu.com'))
print(re.search(r'^w{4}\.s{3}\.com.{3}[0-9]*$', 'wwww.sss.comAAA123'))
#match和search的区别:match只匹配字符串的开始。
phone = '17801112000 this is a phone num'
print(re.sub(r'[^0-9]*', '', phone))  #匹配非数字
date_str = '2017-12-12'
print(re.sub(r'([0-9]{4})-(\d{2})-(\d{2})', r'\2/\3/\1', date_str))
## python3 CGI编程 关于web
## python3 mysql
# 没安装mysql,回头将联想刷成linux CentOS
'''
db = pymysql.connect("localhost","testuser","test123","TESTDB")
cusor = db.cursor()
Example #42
0
import calendar  
# Enter the month and year  
yy = int(input("Enter year: "))  
mm = int(input("Enter month (in numbers): "))  
  
# display the calendar  
print(calendar.month(yy,mm))  
Example #43
0
it should use today’s date to get the month and year.
"""

import sys
import calendar
from datetime import datetime

err = print("Month and year must be entered in the format: mm [yyyy]")

if len(sys.argv) == 1:
    m = datetime.now().month
    y = datetime.now().year
elif len(sys.argv) == 2:
    if sys.argv[1].isdigit() and len(sys.argv[1]) == 2 and int(sys.argv[1]) < 13:
        m = sys.argv[1]
        y = datetime.now().year
    else:
        err
        exit()
elif len(sys.argv) == 3:
    if sys.argv[1].isdigit() and len(sys.argv[1]) == 2 and int(sys.argv[1]) <= 12 and sys.argv[2][1:5].isdigit() and len(sys.argv[2]) == 6:
        (m) = sys.argv[1]
        (y) = sys.argv[2][1:5]
    else:
        err
        exit()
else:
    err
    exit()
print(calendar.month(int(y), int(m)))
Example #44
0
# Python Tanggal dan Waktu

import time
import calendar

# TICK
# Tick adalah interval waktu dengan satuan detik

ticks = time.time()
print("Berjalan sejak 12:00am, January 1, 1970:", ticks)

localtime = time.localtime(time.time())
print("Waktu Lokal Saat ini:", localtime)

# fungsi asctime mendapatkan waktu yg mudah di baca
localtime = time.asctime(time.localtime(time.time()))
print("Waktu Lokal Saat ini:", localtime)

cal = calendar.month(2021, 5)
print(cal)
}  #year1993,april,day6,15:23:15pm, 0 for don;t know which day of the week
#print mytuple
#print time.mktime(mytuple)  #should return 734089995.0
#???having issues
#print time.localtime(time.mktime(mytuple))

#SLEEP Function
#delays excutuin of the calling function or the script by a given number of seconds
time.sleep(7)
print "Hello world!"  #Hello World get displayed after 7 seconds

#Month Method
#requires calander module
import calendar
#takes two arguments, 1st year value and 2nd month value
print calendar.month(1965, 3)
""""     March 1965
Mo Tu We Th Fr Sa Su
 1  2  3  4  5  6  7
 8  9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
"""
#to see calender of the entire year
print calendar.calendar(
    1994, 2, 1, 10
)  #2 is max width for each date, 1 as each week occupy max one line,10 as charcter space between each coloumn
""""
                                      1994
Example #46
0
    sumOfItems = sumOfItems + index
    index = index + 1
else:
    print("Conditional false else")
print("The sumOfItems is", sumOfItems)

#Time functions
timeInstance = time.localtime(time.time())
print("Local current time :", timeInstance)

#Formattng Time according to the user requirement
timeInstance = time.asctime(time.localtime(time.time()))
print("Local current time :", timeInstance)

#To Display calender of the respective month
calenderInstance = calendar.month(2017, 2)
print(calenderInstance)


# Function is a group of related statements that perform a specific task
# Function creation (def is a keyword) def functionname(parameter1,parameter2):
def greet(name):
    """This content is a docstring,generally docstrings are
     enclosed within triple quoteswhich can extend
                 up to multiple lines , this is strored in __doc__
     attribute"""
    print("Good morning ", name)


greet("Samwell Tarly")
Example #47
0
_author__ = "Dilipbobby"

import calendar

# Enter the month and year
year = int(input("Enter year: "))
month = int(input("Enter month: "))

# display the calendar
print(calendar.month(year, month))
Example #48
0
def printCalendar(year: int):
    for i in range(12):
        print(calendar.month(year, i + 1))
    return
Example #49
0
import calendar
print(calendar.weekheader(3))
print()
print(calendar.firstweekday())
print()
print(calendar.month(2020, 2, w=3))
print()
print(calendar.monthcalendar(2020, 2))
print()
print(calendar.calendar(2020, w=3))

for c in range(1, 13):
    print(calendar.monthcalendar(2020, c))

day_of_the_week = calendar.weekday(2020, 1, 31)

print(day_of_the_week)

is_leap = calendar.isleap(2020)
print(is_leap)

how_many_leap_years = calendar.leapdays(2000, 2021)
print(how_many_leap_years)
Example #50
0
        even.append(number)
    else:
        odd.append(number)
print(even)
print(odd)

import time
print(time.localtime(time.time()))
print(time.asctime(time.localtime(time.time())))
# print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
print(time.time())
print(time.tzname)

import calendar

cal = calendar.month(2018, 5)
print("以下输出2016年1月份的日历:")
print(cal)


def getdate():
    print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))


getdate()


def change_args(str):
    str = 20

import calendar
import time

print("-----SELAMAT DATANG DI APLIKASI KALENDER DAN WAKTU-----")
print("1. Lihat Waktu Sekarang")
print("2. Lihat Kalender Berdasarkan Bulan")
print("3. Lihat Kalender 1 Tahun")
pilih=input("Silahkan masukkan no pilihan:")

if pilih =="1":
    localtime = time.localtime(time.time())
    print ("Waktu lokal saat ini :", localtime)
elif pilih == "2":
    kbulanini = int(input("Masukkan bulan[angka] :"))
    ktahunini = int(input("Masukkan tahun[angka] :"))
    cal = calendar.month(ktahunini,kbulanini)
    print ("Dibawah ini adalah kalender:", cal)
elif pilih == "3":
    jtahun = int(input("Masukkan tahun [angka] :"))
    call = calendar.calendar(jtahun,w=2,l=1,c=6)
    print ("Dibawah ini adalah kalender pertahun:", call)
else:
    print ("Fitur belum tersedia")
Example #52
0
def yueli():
    print('---------------------------------')
    yy = int(input("输入年份: "))
    mm = int(input("输入月份: "))

    print(calendar.month(yy, mm))
Example #53
0
"""
Created on Fri May  1 06:37:40 2020

@author: kkunal

Write a Python program to print the calendar of a given month and year.
Note : Use 'calendar' module.

Output:
    
Enter the year : 2020

Enter the month : 05


      May 2020
Mo Tu We Th Fr Sa Su
             1  2  3
 4  5  6  7  8  9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
"""

import calendar

y = int(input("Enter the year : "))
m = int(input("Enter the month : "))
print("\n")
print(calendar.month(y, m))
Example #54
0
 - Otherwise, print a usage statement to the terminal indicating
   the format that your program expects arguments to be given.
   Then exit the program.
"""

import sys
import calendar
from datetime import datetime

yy = input("Input Year: ")
mm = input("Input Month: ")

if(yy == "") and (mm == ""):
    yy = datetime.now().year
    mm = datetime.now().month
    output = calendar.month(yy, mm)
    print(output)

elif (yy == "") and (mm.isdigit()):
    yy = datetime.now().year
    mm = int(mm)
    output = calendar.month(yy, mm)
    print(output)

elif (yy.isdigit()) and (mm == ""):
    foo = int(yy)
    fee = datetime.now().month
    output = calendar.month(yy, fee)
    print(output)

elif (yy.isdigit()) and (mm.isdigit()):
Example #55
0
def show_calendar(year, month):
    print(calendar.month(year, month))
Example #56
0
#时间格式化
import time
# 格式化成2016-03-20 11:45:39形式
print( time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())  )
# 格式化成Sat Mar 28 22:24:24 2016形式
print( time.strftime("%a %b %d %H:%M:%S %Y", time.localtime())  )
# 将格式字符串转换为时间戳
a = "Sat Mar 28 22:24:24 2016"
print( time.mktime(time.strptime(a,"%a %b %d %H:%M:%S %Y")) )
timestamp = time.mktime(time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()))
# 获取当前时间时间戳
int(time.time()*1000)

import calendar
cal = calendar.month(2016, 1)
print( "以下输出2016年1月份的日历:" )
print( cal )

"""
%y 两位数的年份表示(00-99)
%Y 四位数的年份表示(000-9999)
%m 月份(01-12)
%d 月内中的一天(0-31)
%H 24小时制小时数(0-23)
%I 12小时制小时数(01-12)
%M 分钟数(00=59)
%S 秒(00-59)
%a 本地简化星期名称
%A 本地完整星期名称
%b 本地简化的月份名称
Example #57
0
def printCalendar(year, month):
    print(calendar.month(year, month))
Example #58
0
import calendar
print(calendar.month(2020, 9))

print('Year :')
print(calendar.calendar(2000, 4, 1, 9))
print(calendar.day_name)
Example #59
0
def getCalendar():
    print(calendar.month(2019, 7))
Example #60
0
    Field           Values
    Hour            0 to 23
    Minute          0 to 59
    Second          0 to 61 (60 or 61 are leap-seconds)
    Day of Week     0 to 6 (0 is Monday)
    Day of Year     1 to 366 (Julien Day)
#-------------------------------------------------------#
'''
print 'Local Current Time =', time.localtime(
    time.time()
)  # time.struct_time(tm_year=2017, tm_mon=12, tm_mday=26, tm_hour=16, tm_min=18, tm_sec=26, tm_wday=1, tm_yday=360, tm_isdst=0)
# tm_yday = 1 to 366 (Julien Day)

print '''
#--------------struct_time Structure--------------------#
tm_year	    2008
tm_mon	    1 to 12
tm_mday	    1 to 31
tm_hour	    0 to 23
tm_min	    0 to 59
tm_sec	    0 to 61 (60 or 61 are leap-seconds)
tm_wday	    0 to 6 (0 is Monday)
tm_yday	    1 to 366 (Julian day)
tm_isdst    -1, 0, 1, -1 means library determines DST
#--------------------------------------------------------#
'''
print 'Getting Formatted Time =', time.asctime(time.localtime(
    time.time()))  # Tue Dec 26 16:18:26 2017

print calendar.month(2018, 1)