Python Time module and datetime module

Source: Internet
Author: User
Tags element groups local time month name timedelta
First, the time module
 There are three main formats for time representation in the time module:

A, timestamp timestamp, the timestamp represents the offset calculated in seconds starting from January 1, 1970, 00:00:00

B, struct_time time tuple, a total of nine element groups.

C, format time Format time, the formatted structure makes time more readable. Includes custom and fixed formats.

1. Time format conversion diagram:

 

#! / usr / bin / env python
#-*-coding: utf-8-*-
# __author__ = "TKQ"

import time

# Generate timestamp
time.time ()
# 1477471508.05
#struct_time to timestamp
time.mktime (time.localtime ())
#Generate struct_time
# timestamp to struct_time local time
time.localtime ()
time.localtime (time.time ())
# time.struct_time (tm_year = 2016, tm_mon = 10, tm_mday = 26, tm_hour = 16, tm_min = 45, tm_sec = 8, tm_wday = 2, tm_yday = 300, tm_isdst = 0)

# timestamp to struct_time Greenwich Mean Time
time.gmtime ()
time.gmtime (time.time ())
# time.struct_time (tm_year = 2016, tm_mon = 10, tm_mday = 26, tm_hour = 8, tm_min = 45, tm_sec = 8, tm_wday = 2, tm_yday = 300, tm_isdst = 0)

#format_time to struct_time
time.strptime (‘2011-05-05 16:37:06’, ‘% Y-% m-% d% X’)
# time.struct_time (tm_year = 2011, tm_mon = 5, tm_mday = 5, tm_hour = 16, tm_min = 37, tm_sec = 6, tm_wday = 3, tm_yday = 125, tm_isdst = -1)

#Generate format_time
#struct_time to format_time
time.strftime ("% Y-% m-% d% X")
time.strftime ("% Y-% m-% d% X", time.localtime ())
# 2016-10-26 16:48:41


#Generate a fixed format time representation format
time.asctime (time.localtime ())
time.ctime (time.time ())
# Wed Oct 26 16:45:08 2016


Attribute value
tm_year (year) such as 2011
tm_mon (month) 1-12
tm_mday (Sun) 1-31
tm_hour (hours) 0-23
tm_min (minutes) 0-59
tm_sec (seconds) 0-61
tm_wday (weekday) 0-6 (0 means Sunday)
tm_yday (day of the year) 1-366
tm_isdst (whether it is daylight saving time) The default is -1


format time structured representation

Format Meaning
% a locale simplified week name
% A local full week name
% b local simplified month name
% B local full month name
% c local corresponding date and time representation
% d day of the month (01-31)
% H Hour of day (24-hour clock, 00-23)
% I first hour (12-hour clock, 01-12)
% j day of the year (001-366)
% m month (01-12)
% M minutes (00-59)
% p corresponding to local am or pm
% S seconds (01-61)
% U Week of the year. (00-53 Sunday is the beginning of a week.) All days before the first Sunday are placed in week 0.
% w day of the week (0-6, 0 is Sunday)
% W and% U are basically the same, except that% W starts with Monday as a week.
% x local corresponding date
% X local corresponding time
% y year with century removed (00-99)
% Y full year
% Z name of the time zone (null if not present)
%% ‘%’ character
Common structured time combinations:

print time.strftime ("% Y-% m-% d% X")
# 2016-10-26 20:50:13
3, time addition and subtraction

#timestamp Addition and Subtraction Units in Seconds
import time
t1 = time.time ()
t2 = t1 + 10

print time.ctime (t1) #Wed Oct 26 21:15:30 2016
print time.ctime (t2) #Wed Oct 26 21:15:40 2016
Second, the datetime module
The datatime module repackages the time module and provides more interfaces. The classes provided are: date, time, datetime, timedelta, tzinfo.

1.date class

datetime.date (year, month, day)

Static methods and fields

date.max, date.min: the maximum and minimum dates that a date object can represent;
date.resolution: The smallest unit of a date object representing a date. Here is the day.
date.today (): returns a date object representing the current local date;
date.fromtimestamp (timestamp): returns a date object according to the given time;

from datetime import *
import time

print ‘date.max:’, date.max
print ‘date.min:’, date.min
print ‘date.today ():‘, date.today ()
print ‘date.fromtimestamp ():’, date.fromtimestamp (time.time ())

#Output =======================
# date.max: 9999-12-31
# date.min: 0001-01-01
# date.today (): 2016-10-26
# date.fromtimestamp (): 2016-10-26

output
Methods and properties

d1 = date (2011,06,03) #date object
d1.year, date.month, date.day: year, month, day;
d1.replace (year, month, day): generate a new date object, replacing the attributes in the original object with the year, month, and day specified by the parameters. (The original object remains unchanged)
d1.timetuple (): returns the time.struct_time object corresponding to the date;
d1.weekday (): returns weekday, if it is Monday, it returns 0; if it is week 2, it returns 1, and so on;
d1.isoweekday (): returns weekday, if it is Monday, returns 1; if it is week 2, returns 2, and so on;
d1.isocalendar (): returns a tuple in the format (year, month, day);
d1.isoformat (): Returns a string with a format such as 'YYYY-MM-DD';
d1.strftime (fmt): Same as the time module format.


from datetime import *

now = date (2016, 10, 26)
tomorrow = now.replace (day = 27)
print ‘now:‘, now, ‘, tomorrow:’, tomorrow
print ‘timetuple ():‘, now.timetuple ()
print ‘weekday ():‘, now.weekday ()
print ‘isoweekday ():’, now.isoweekday ()
print ‘isocalendar ():’, now.isocalendar ()
print ‘isoformat ():’, now.isoformat ()
print ‘strftime ():‘, now.strftime ("% Y-% m-% d")

#Output ==========================
# now: 2016-10-26, tomorrow: 2016-10-27
# timetuple (): time.struct_time (tm_year = 2016, tm_mon = 10, tm_mday = 26, tm_hour = 0, tm_min = 0, tm_sec = 0, tm_wday = 2, tm_yday = 300, tm_isdst = -1)
# weekday (): 2
# isoweekday (): 3
# isocalendar (): (2016, 43, 3)
# isoformat (): 2016-10-26
# strftime (): 2016-10-26

output
2, time class

datetime.time (hour [, minute [, second [, microsecond [, tzinfo]]]])

Static methods and fields

time.min, time.max: the minimum and maximum time that the time class can represent. Where time.min = time (0, 0, 0, 0) and time.max = time (23, 59, 59, 999999);
time.resolution: the smallest unit of time, here is 1 microsecond;
Methods and properties

t1 = datetime.time (10,23,15) #time object
t1.hour, t1.minute, t1.second, t1.microsecond: hours, minutes, seconds, microseconds;
t1.tzinfo: time zone information;
t1.replace ([hour [, minute [, second [, microsecond [, tzinfo]]]]]): Create a new time object, replacing the original object with the hour, minute, second, and microsecond specified by the parameters Properties (the original object remains unchanged);
t1.isoformat (): Returns a string representation in the format "HH: MM: SS";
t1.strftime (fmt): same as the format in the time module;


from datetime import *

tm = time (23, 46, 10)
print ‘tm:‘, tm
print ‘hour:% d, minute:% d, second:% d, microsecond:% d’% (tm.hour, tm.minute, tm.second, tm.microsecond)
tm1 = tm.replace (hour = 20)
print ‘tm1:’, tm1
print ‘isoformat ():’, tm.isoformat ()
print ‘strftime ()‘, tm.strftime ("% X")

#Output ===================================================
# tm: 23:46:10
# hour: 23, minute: 46, second: 10, microsecond: 0
# tm1: 20:46:10
# isoformat (): 23: 46: 1
0
# strftime () 23:46:10

output


3, datetime class

datetime is equivalent to the combination of date and time.
datetime.datetime (year, month, day [, hour [, minute [, second [, microsecond [, tzinfo]]]]])

Static methods and fields

datetime.today (): returns a datetime object representing the current local time;
datetime.now ([tz]): returns a datetime object representing the current local time. If the parameter tz is provided, the local time in the time zone indicated by the tz parameter is obtained
datetime.utcnow (): Returns a datetime object for the current UTC time; #Greenwich Mean Time
datetime.fromtimestamp (timestamp [, tz]): create a datetime object according to the time, the parameter tz specifies the time zone information;
datetime.utcfromtimestamp (timestamp): create a datetime object based on the time;
datetime.combine (date, time): create a datetime object based on date and time;
datetime.strptime (date_string, format): convert the format string into a datetime object;


from datetime import *
import time

print ‘datetime.max:’, datetime.max
print ‘datetime.min:’, datetime.min
print ‘datetime.resolution:’, datetime.resolution
print ‘today ():‘, datetime.today ()
print ‘now ():‘, datetime.now ()
print ‘utcnow ():‘, datetime.utcnow ()
print ‘fromtimestamp (tmstmp):’, datetime.fromtimestamp (time.time ())
print ‘utcfromtimestamp (tmstmp):’, datetime.utcfromtimestamp (time.time ())

#output ========================
# datetime.max: 9999-12-31 23: 59: 59.999999
# datetime.min: 0001-01-01 00:00:00
# datetime.resolution: 0: 00: 00.000001
# today (): 2016-10-26 23: 12: 51.307000
# now (): 2016-10-26 23: 12: 51.307000
# utcnow (): 2016-10-26 15: 12: 51.307000
# fromtimestamp (tmstmp): 2016-10-26 23: 12: 51.307000
# utcfromtimestamp (tmstmp): 2016-10-26 15: 12: 51.307000

output
Methods and properties

dt = datetime.now () # datetime object
dt.year, month, day, hour, minute, second, microsecond, tzinfo:
dt.date (): Get the date object;
dt.time (): Get the time object;
dt. replace ([year [, month [, day [, hour [, minute [, second [, microsecond [, tzinfo]]]]]]]]):
dt. timetuple ()
dt. utctimetuple ()
dt. toordinal ()
dt. weekday ()
dt. isocalendar ()
dt. isoformat ([sep])
dt. ctime (): returns a date format C string, equivalent to time.ctime (time.mktime (dt.timetuple ()))
dt. strftime (format)


4.timedelta class, time addition and subtraction

Using timedelta, you can easily calculate days, hours, minutes, seconds, milliseconds, and delicate time on the date. If you want to calculate the month, you need another method.

#coding: utf-8
from datetime import *

dt = datetime.now ()
#Date minus one day
dt1 = dt + timedelta (days = -1) # yesterday
dt2 = dt-timedelta (days = 1) # yesterday
dt3 = dt + timedelta (days = 1) # tomorrow
delta_obj = dt3-dt
print type (delta_obj), delta_obj # <type ‘datetime.timedelta‘> 1 day, 0:00:00
print delta_obj.days, delta_obj.total_seconds () # 1 86400.0
5, tzinfo time zone class

#! / usr / bin / python
# coding = utf-8

from datetime import datetime, tzinfo, timedelta

"" "
tzinfo is a class about time zone information
tzinfo is an abstract class, so it cannot be instantiated directly
"" "
class UTC (tzinfo):
    "" "UTC" ""
    def __init __ (self, offset = 0):
        self._offset = offset

    def utcoffset (self, dt):
        return timedelta (hours = self._offset)

    def tzname (self, dt):
        return "UTC +% s"% self._offset

    def dst (self, dt):
        return timedelta (hours = self._offset)

#Beijing time
beijing = datetime (2011,11,11,0,0,0, tzinfo = UTC (8))
print "beijing time:", beijing
#Bangkok Time
bangkok = datetime (2011,11,11,0,0,0, tzinfo = UTC (7))
print "bangkok time", bangkok
#Beijing Time to Bangkok Time
print "beijing-time to bangkok-time:", beijing.astimezone (UTC (7))

#The time zone is also considered when calculating the time difference
timespan = beijing-bangkok
print "Time difference:", timespan

#Output ====================
# beijing time: 2011-11-11 00: 00: 00 + 08: 00
# bangkok time 2011-11-11 00: 00: 00 + 07: 00
# beijing-time to bangkok-time: 2011-11-10 23: 00: 00 + 07: 00
# Time difference: -1 day, 23:00:00


Python time module and datetime module

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.