Basic grammar of python learning (Part 5)

Basic grammar of python learning (Part 5)

  1. python date and time

// python provides a time and calendar module that can be used to format dates and times.

// The interval is a floating point decimal in seconds.

// Each timestamp is expressed as how much time has passed since midnight (epoch) on January 1, 1970.

// There are many functions under Python's time module to convert common date formats. For example, the function time.time() is used to obtain the current timestamp,

// The following example:

#!/usr/bin/env

import time;   # Import the time module

ticks = time.time()
print ( "The current timestamp is:" , ticks)

// Timestamp units are best for date arithmetic. But dates before 1970 cannot be represented in this way. Neither is a date too far away, UNIX and Windows only support until 2038.

  1. Time tuple
serial number field value
0 4 digit year 2008
1 moon 1 to 12
2 Day 1 to 31
3 Hour 0 to 23
4 minute 0 to 59
5 second 0 to 61 (60 or 61 is a leap second)
6 day of the week 0 to 6 (0 is Monday)
7 day of the year 1 to 366 (Julian calendar)
8 summer time -1, 0, 1, -1 is the flag that determines whether it is daylight saving time

// The above is also a struct_time tuple. This structure has the following properties:

serial number Attributes value
0 tm_year 2008
1 tm_mon
2 tm_mday 1 to 31
3 tm_hour 0 to 23
4 tm_min 0 to 59
5 tm_sec 0 to 61 (60 or 61 is a leap second)
6 tm_wday 0 to 6 (0 is Monday)
7 tm_yday 1 to 366 (Julian calendar)
8 tm_isdst -1, 0, 1, -1 is the flag that determines whether it is daylight saving time
  1. Get the current time

// To convert from a time-staggered way of returning a float to a time tuple, just pass the float to a function such as localtime .

import time

localtime = time.localtime(time.time())
 print ( "The local time is:" , localtime )

// output result is

The local time is: time.struct_time(tm_year= 2016 , tm_mon= 4 , tm_mday= 7 , tm_hour= 10 , tm_min= 3 , tm_sec= 27 , tm_wday= 3 , tm_yday= 98 , tm_isdst= 0 )

// get formatted time

// You can choose any format according to your needs, but the easiest function to get a readable time mode is asctime():

localtime = time.asctime( time.localtime(time.time()) )
 print ( "The local time is:" , localtime )

// The output is:

Local time: Thu Apr   7  10 : 05 : 21  2016

// format the date

// We can format the date using the strftime method of the time module:

time.strftime(format[, t])

# Format to 2016-03-20 11:45:39 format 
print time.strftime( "%Y-%m-%d %H:%M:%S" , time.localtime())

# Formatted as Sat Mar 28 22:24:24 2016 
print time.strftime( "%a %b %d %H:%M:%S %Y" , time.localtime())

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

// The output of the above example is:

2016-04-07 10:25:09
Thu Apr 07 10:25:09 2016
1459175064.0

// Time and date formatting symbols in python:

  • %y Two-digit year representation (00-99)
  • %Y Four-digit year representation (000-9999)
  • %m month (01-12)
  • %d day of the month (0-31)
  • %H 24-hour hour (0-23)
  • %I 12-hour clock (01-12)
  • %M minutes (00=59)
  • %S seconds (00-59)
  • %a local abbreviated weekday name
  • %A local full week name
  • %b local abbreviated month name
  • %B local full month name
  • %c Local corresponding date representation and time representation
  • Day of the year in %j (001-366)
  • %p local AM or PM equivalent
  • %U Week of the year (00-53) Sunday is the start of the week
  • %w week (0-6), Sunday is the start of the week
  • %W Week of the year (00-53) Monday is the start of the week
  • %x local corresponding date representation
  • %X local corresponding time representation
  • %Z The name of the current time zone
  • %% % sign itself

  • Get a month’s calendar

//  The Calendar module has a wide range of methods for handling yearly and monthly calendars, such as printing the monthly calendar for a month: 

#!/usr/bin/env

import calendar

cal = calendar.month(2016, 1) 
print("The following outputs the calendar for January 2016 : ") 
print(cal);

//  The above example outputs the result:

The following outputs the calendar for January 2016 :
    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

  1. Time module
serial number function describe
1 time.altzone Returns the offset in seconds for the daylight saving time zone west of Greenwich. Returns a negative value if the region is east of Greenwich (eg Western Europe, including the UK). Only available for regions with daylight saving time enabled.
2 time.asctime([tupletime]) Accepts a time tuple and returns a readable 24-character string of the form “Tue Dec 11 18:07:14 2008” (Tue Dec 11 2008 18:07:14).
3 time.clock( ) Returns the current CPU time in seconds as a floating point number. Used to measure the time spent in different programs, more useful than time.time().
4 time.ctime([secs]) The function is equivalent to asctime(localtime(secs)), and the parameter is not given is equivalent to asctime()
5 time.gmtime([secs]) Receives a time dropout (floating-point seconds elapsed since the 1970 epoch) and returns a time tuple t in Greenwich astronomical time. Note: t.tm_isdst is always 0
6 time.localtime([secs]) Receives a time stamp (floating point seconds since the 1970 epoch) and returns a time tuple t in local time (t.tm_isdst can take 0 or 1, depending on whether the local time is daylight saving time).
7 time.mktime(tupletime) Takes a time tuple and returns the time dropout (floating point seconds elapsed since the 1970 epoch).
8 time.sleep(secs) Delay the running of the calling thread, secs is the number of seconds.
9 time.strftime(fmt[,tupletime]) Takes a time tuple and returns the local time as a human-readable string in the format determined by fmt.
10 time.strptime(str,fmt=’%a %b %d %H:%M:%S %Y’) Parses a time string into a time tuple according to the format of fmt.
11 time.time( ) Returns the timestamp of the current time (floating point seconds since the 1970 epoch).
12 time.tzset() Time-related settings are reinitialized according to the environment variable TZ.
13 time.timezone The property time.timezone is the offset in seconds from Greenwich for the local time zone (without daylight saving time enabled) (>0, America; <=0 most of Europe, Asia, Africa).
14 time.tzname The property time.tzname contains a pair of strings that vary depending on the situation, the name of the local time zone with daylight saving time, and without.
  1. Calendar module

// The functions of this module are all calendar related, such as printing the character monthly calendar of a certain month. 
// Monday is the default first day of the week, Sunday is the default last day. To change the setting, call the calendar.setfirstweekday() function. The module contains the following built-in functions:

serial number function describe
1 calendar.calendar(year,w=2,l=1,c=6) Returns a year calendar in a multi-line string format, with 3 months per line, separated by a distance of c. The daily width interval is w characters. The length of each line is 21* W+18+2* C. l is the number of rows per week.
2 calendar.firstweekday( ) Returns the current weekly start date setting. By default, 0 is returned when the caendar module is first loaded, which is Monday.
3 calendar.isleap(year) Returns True if it is a leap year, false otherwise.
4 calendar.leapdays(y1,y2) Returns the total number of leap years between Y1 and Y2.
5 calendar.month(year,month,w=2,l=1) Returns a year month month calendar in a multi-line string format, with two lines of headers and one line per week. The daily width interval is w characters. The length of each line is 7*w+6. l is the number of rows per week.
6 calendar.monthcalendar(year,month) Returns a single-level nested list of integers. Each sublist is loaded with an integer representing a week. Dates outside the month of year are set to 0; days within the range are indicated by the day of the month, starting with 1.
7 calendar.monthrange(year,month) Returns two integers. The first is the date code for the day of the week for the month, and the second is the date code for the month. Day is from 0 (Monday) to 6 (Sunday); month is from 1 to 12.
8 calendar.prcal(year,w=2,l=1,c=6) Equivalent to print calendar.calendar(year,w,l,c).
9 calendar.prmonth(year,month,w=2,l=1) Equivalent to print calendar.calendar(year, w, l, c).
10 calendar.setfirstweekday(weekday) Set the weekly start date code. 0 (Monday) to 6 (Sunday).
11 calendar.timegm(tupletime) Contrary to time.gmtime: accepts a time tuple form, returns the time stamp (floating point seconds elapsed since 1970 epoch) at that moment.
12 calendar.weekday(year,month,day) Returns the date code for the given date. 0 (Monday) to 6 (Sunday). The months are 1 (January) to 12 (December).
  1. Other related modules and functions
    In Python, other modules that deal with date and time are:

  2. datetime module

  3. pytz module

  4. dateutil module

    1. Use the datetime module to get the current date and time

#!/usr/bin/env
# -*- coding: UTF-8 -*-

import datetime
i = datetime.datetime.now()
print ( "The current date and time is %s" % i)
 print ( "The date and time in ISO format is %s" % i.isoformat() )
 print ( "The current year is %s" %i.year)
 print ( "The current month is %s" %i.month)
 print ( "The current date is %s" %i.day)
 print ( "The format of dd/mm/yyyy is %s/%s/%s" % (i.day, i.month, i.year) )
 print ( "The current hour is %s" %i.hour)
 print ( "The current minute is %s" %i.minute)
 print ( "The current second is %s " %i.second)

Leave a Comment

Your email address will not be published. Required fields are marked *