A comprehensive summary of Python's handling of dates and times
Source | Traffic State
Knowing Circle | To enter the “computing platform group”, please add micro yanzhi-6, note calculation
Python’s time processing module is used a lot in daily use, but basically it is necessary to check data when using it, which is still a little troublesome. After sorting it out, it is convenient for future use.
Table of contents
- time related concepts
- Python time module
- time formatting
- Timer function
- Other built-in functions of the time module
Attributes contained in the time module
datetime module
date class
time class
datetime class
class timedelta
tzinfo class
pytz module
time zone conversion
Daylight Savings Time Handling
dateutil module
parser.parse
rrule.rrule
Arrow
UTC time
local time
parsing time
Unix timestamp
Format date and time
Convert to regional time
working day
moving time
summer time
Humanized date and time
ISO 8601 class
time related concepts
Python time module
- time formatting
- Timer function
- Other built-in functions of the time module
- Attributes contained in the time module
time formatting
Timer function
Other built-in functions of the time module
Attributes contained in the time module
datetime module
- date class
- time class
- datetime class
- class timedelta
- tzinfo class
date class
time class
datetime class
class timedelta
tzinfo class
pytz module
- time zone conversion
- Daylight Savings Time Handling
time zone conversion
Daylight Savings Time Handling
dateutil module
- parser.parse
- rrule.rrule
parser.parse
rrule.rrule
Arrow
- UTC time
- local time
- parsing time
- Unix timestamp
- Format date and time
- Convert to regional time
- working day
- moving time
- summer time
- Humanized date and time
UTC time
local time
parsing time
Unix timestamp
Format date and time
Convert to regional time
working day
moving time
summer time
Humanized date and time
ISO 8601 class
In the Python documentation, time is classified in Generic Operating System Services, in other words, the functionality it provides is closer to the operating system level. Reading through the documentation shows that the time module is built around the Unix Timestamp.
This module mainly includes a class struct_time, several other functions and related constants. It should be noted that most of the functions in this module call the functions of the same name in the C library of the platform where they are located, so pay special attention to some functions that are platform-dependent and may have different effects on different platforms. Another point is that because it is based on Unix Timestamp, the date range that it can represent is limited to 1970 - 2038. If you write code that needs to deal with dates outside the aforementioned range, you may need to consider using datetime. Modules are better.
Get current time and conversion time format
- time returns the time in timestamp format (offset in seconds relative to 1.1 00:00:00)
- ctime returns the time in the form of a string, and the time in timestamp format can be passed in for conversion
- asctime returns the time in the form of a string, you can pass in the time in the form of struct_time for conversion
- localtime returns the struct_time form of the current time, which can be passed in timestamp format time for conversion
- gmtime returns the struct_time form of the current time, UTC time zone (time zone 0), which can be passed in timestamp format time for conversion
time returns the time in timestamp format (offset in seconds relative to 1.1 00:00:00)
ctime returns the time in the form of a string, and the time in timestamp format can be passed in for conversion
asctime returns the time in the form of a string, you can pass in the time in the form of struct_time for conversion
localtime returns the struct_time form of the current time, which can be passed in timestamp format time for conversion
gmtime returns the struct_time form of the current time, UTC time zone (time zone 0), which can be passed in timestamp format time for conversion
>>> time.time
1473386416.954
>>> time.ctime
‘Fri Sep 09 10:00:25 2016’
>>> time.ctime(time.time)
‘Fri Sep 09 10:28:08 2016’
>>> time.asctime
‘Fri Sep 09 10:22:40 2016’
>>> time.asctime(time.localtime)
‘Fri Sep 09 10:33:00 2016’
>>> time.localtime
time.struct_time(tm_year= 2016, tm_mon= 9, tm_mday= 9, tm_hour= 10, tm_min= 1, tm_sec= 19, tm_wday= 4, tm_yday= 253, tm_isdst= 0)
>>> time.localtime(time.time)
time.struct_time(tm_year= 2016, tm_mon= 9, tm_mday= 9, tm_hour= 10, tm_min= 19, tm_sec= 11, tm_wday= 4, tm_yday= 253, tm_isdst= 0)
>>> time.gmtime
time.struct_time(tm_year= 2016, tm_mon= 9, tm_mday= 9, tm_hour= 2, tm_min= 13, tm_sec= 10, tm_wday= 4, tm_yday= 253, tm_isdst= 0)
>>> time.gmtime(time.time)
time.struct_time(tm_year= 2016, tm_mon= 9, tm_mday= 9, tm_hour= 2, tm_min= 15, tm_sec= 35, tm_wday= 4, tm_yday= 253, tm_isdst= 0)
struct_time has a total of 9 elements, of which the first 6 are the year, month, day, hour, minute and second, and the last three represent the meanings:
- tm_wday Day of the week (Sunday is 0)
- tm_yday Day of the year
- Whether tm_isdst is daylight saving time
tm_wday Day of the week (Sunday is 0)
tm_yday Day of the year
Whether tm_isdst is daylight saving time
time.mktime
Convert a timestamp in struct_time format
>>> time.mktime(time.localtime)
1473388585.0
time.strftime(format[,t]) converts a struct_time time to a formatted time string. If t is not specified, time.localtime will be passed in. If any element in the tuple is out of bounds, a ValueError will be thrown.
- %c local corresponding date and time representation
- %x local corresponding date
- %X local response time
- %y removes the year from the century (00 - 99)
- %Y full year
- %m month (01 – 12)
- %b local abbreviated month name
- %B local full month name
- %d Day of the month (01 – 31)
- %j Day of the year (001 – 366)
- %U Week of the year. (Sunday 00 – 53 is the start of a week.) All days before the first Sunday are placed in week 0.
- %W and %U are basically the same, except that %W starts the week on Monday.
- %w Day of the week (0 - 6, 0 is Sunday)
- %a locale abbreviated weekday name
- %A local full week name
- %H Hour of the day (24-hour clock, 00 – 23)
- %I number of hours (12-hour clock, 01 – 12)
- %p The corresponding character of local am or pm, “%p” is only effective when used in conjunction with “%I”.
- %M minutes (00 – 59)
- %S seconds (01 - 61), the document emphasizes that it is indeed 0 - 61, not 59, leap year seconds account for two seconds
- %Z time zone name (null character if not present)
- %% ‘%’ character
%c local corresponding date and time representation
%x local corresponding date
%X local response time
%y removes the year from the century (00 - 99)
%Y full year
%m month (01 – 12)
%b local abbreviated month name
%B local full month name
%d Day of the month (01 – 31)
%j Day of the year (001 – 366)
%U Week of the year. (Sunday 00 – 53 is the start of a week.) All days before the first Sunday are placed in week 0.
%W and %U are basically the same, except that %W starts the week on Monday.
%w Day of the week (0 - 6, 0 is Sunday)
%a locale abbreviated weekday name
%A local full week name
%H Hour of the day (24-hour clock, 00 – 23)
%I number of hours (12-hour clock, 01 – 12)
%p The corresponding character of local am or pm, “%p” is only effective when used in conjunction with “%I”.
%M minutes (00 – 59)
%S seconds (01 - 61), the document emphasizes that it is indeed 0 - 61, not 59, leap year seconds account for two seconds
%Z time zone name (null character if not present)
%% ‘%’ character
‘2016-09-09 10:54:21’
time.strptime(string[,format])
Converts a formatted time string to struct_time. Actually it is the inverse of strftime.
>>> time.strptime(time.ctime)
time.struct_time(tm_year= 2016, tm_mon= 9, tm_mday= 9, tm_hour= 11, tm_min= 0, tm_sec= 4, tm_wday= 4, tm_yday= 253, tm_isdst= -1)
Timer function
time.sleep(secs)
The thread delays running for the specified time. The unit is seconds.
time.clock
It should be noted that this has different meanings on different systems. On UNIX systems, it returns the “process time”, which is a floating point number (timestamp) in seconds. In WINDOWS, the first call returns the actual time the process is running. The call after the second time is the elapsed time since the first call. (Actually based on QueryPerformanceCounter on WIN32, which is more precise than milliseconds)
importtime
time.sleep( 1)
print( “clock1:%s”% time.clock)
time.sleep( 1)
print( “clock2:%s”% time.clock)
time.sleep( 1)
print( “clock3:%s”% time.clock)
The running result is:
clock1: 1.57895443216e-06
clock2: 1.00064381867
clock3: 2.00158724394
The first clock outputs the program running time, and the second and third clock outputs are the time interval from the first clock
Other built-in functions of the time module
- 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.
- tzset reinitializes time-related settings according to the environment variable TZ.
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.
tzset reinitializes time-related settings according to the environment variable TZ.
- timezone is the offset in seconds from Greenwich in the local time zone (without DST enabled) (>0, Americas; <=0 most of Europe, Asia, Africa).
- tzname contains a pair of strings that vary depending on the situation, the name of the local time zone with and without daylight saving time.
timezone is the offset in seconds from Greenwich in the local time zone (without DST enabled) (>0, Americas; <=0 most of Europe, Asia, Africa).
tzname contains a pair of strings that vary depending on the situation, the name of the local time zone with and without daylight saving time.
print(time.timezone)
print(time.tzname)
print(time.tzname[ 0].decode( “GBK”))
print(time.tzname[ 1].decode( “GBK”))
operation result
-28800
( ‘\xd6\xd0\xb9\xfa\xb1\xea\xd7\xbc\xca\xb1\xbc\xe4’, ‘\xd6\xd0\xb9\xfa\xcf\xc4\xc1\xee\xca\xb1’)
China Standard Time
China Summer Time
datetime module
datetime is much more advanced than time, it can be understood that datetime is encapsulated based on time and provides more practical functions.
The datetime module defines the following classes:
- date: A class representing a date. Commonly used attributes are year, month, day
- time: A class representing time. Commonly used attributes are hour, minute, second, microsecond
- datetime: Indicates datetime
- timedelta: represents the time interval, that is, the length between two time points
- tzinfo: relevant information about time zones
date: A class representing a date. Commonly used attributes are year, month, day
time: A class representing time. Commonly used attributes are hour, minute, second, microsecond
datetime: Indicates datetime
timedelta: represents the time interval, that is, the length between two time points
tzinfo: relevant information about time zones
Note: Objects of the above types are immutable.
date class
The date class defines some common class methods and class attributes:
- max, min: the maximum and minimum dates that the date object can represent
- resolution: The smallest unit in which the date object represents the date. here is the day
- today: returns a date object representing the current local date
- fromtimestamp(timestamp): Returns a date object based on the given time stamp
- fromordinal(ordinal): Convert Gregorian calendar time to date object (not used for special calendars)
max, min: the maximum and minimum dates that the date object can represent
resolution: The smallest unit in which the date object represents the date. here is the day
today: returns a date object representing the current local date
fromtimestamp(timestamp): Returns a date object based on the given time stamp
fromordinal(ordinal): Convert Gregorian calendar time to date object (not used for special calendars)
importtime
print( ‘date.max:‘, date.max)
print( ‘date.min:‘, date.min)
print( ‘date.resolution:‘, date.resolution)
print( ‘date.today:‘, date.today)
print( ‘date.fromtimestamp:‘, date.fromtimestamp(time.time))
Results of the:
date.max: 9999-12-31
date.min: 0001-01-01
date.resolution: 1day, 0: 00: 00
date.today: 2016-09-12
date.fromtimestamp: 2016-09-12
Instance methods and properties provided by date:
- .year: returns the year
- .month: returns the month
- .day: return day
- .replace(year, month, day): Generate a new date object, replacing the properties in the original object with the year, month, and day specified by the parameters. (The original object remains unchanged)
- .weekday: return weekday, if it is Monday, return 0; if it is week 2, return 1, and so on
- .isoweekday: return weekday, if it is Monday, return 1; if it is week 2, return 2, and so on
- .isocalendar: Return format such as (year, wk num, wk day)
- .isoformat: returns a string in the format ‘YYYY-MM-DD’
- .strftime(fmt): Custom format string. Similar to strftime in the time module.
- .toordinal: Returns the Gregorian Calendar date corresponding to the date
.year: returns the year
.month: returns the month
.day: return day
.replace(year, month, day): Generate a new date object, replacing the properties in the original object with the year, month, and day specified by the parameters. (The original object remains unchanged)
.weekday: return weekday, if it is Monday, return 0; if it is week 2, return 1, and so on
.isoweekday: return weekday, if it is Monday, return 1; if it is week 2, return 2, and so on
.isocalendar: Return format such as (year, wk num, wk day)
.isoformat: returns a string in the format ‘YYYY-MM-DD’
.strftime(fmt): Custom format string. Similar to strftime in the time module.
.toordinal: Returns the Gregorian Calendar date corresponding to the date
today = date.today
print( ‘today:‘, today)
print( ‘.year:‘, today.year)
print( ‘.month:‘, today.month)
print( ‘.replace:‘, today.replace(year= 2017) )
print( ‘.weekday:‘, today.weekday)
print( ‘.isoweekday:‘, today.isoweekday)
print( ‘.isocalendar:‘, today.isocalendar)
print( ‘.isoformat:‘, today.isoformat)
print( ‘.strftime:‘, today.strftime( ‘%Y-%m-%d’) )
print( ‘.toordinal:‘, today.toordinal)
Results of the:
today: 2016-09-12
.year: 2016
.month: 9
.replace: 2017-09-12
.weekday: 0
.isoweekday: 1
.isocalendar: ( 2016, 37, 1)
.isoformat: 2016-09-12
.strftime: 2016-09-12
.toordinal: 736219
date also has overloads for certain operations, which allow us to do the following with dates:
- date2 = date1 + timedelta # date plus an interval, returns a new date object
- date2 = date1 – timedelta # date minus an interval, returns a new date object
- timedelta = date1 – date2 # Subtract two dates and return a time interval object
- date1 < date2 # compare two dates
date2 = date1 + timedelta # date plus an interval, returns a new date object
date2 = date1 – timedelta # date minus an interval, returns a new date object
timedelta = date1 – date2 # Subtract two dates and return a time interval object
date1 < date2 # compare two dates
The constructor of the time class is as follows: (The parameter tzinfo, which represents the time zone information.)
class datetime.time(hour[, minute[, second[, microsecond[, tzinfo]]]])
Class attributes defined by the time class:
- min, max: The minimum and maximum time that the time class can represent. where time.min = time(0, 0, 0, 0), time.max = time(23, 59, 59, 999999)
- resolution: the smallest unit of time, here is 1 microsecond
min, max: The minimum and maximum time that the time class can represent. where time.min = time(0, 0, 0, 0), time.max = time(23, 59, 59, 999999)
resolution: the smallest unit of time, here is 1 microsecond
Instance methods and properties provided by the time class:
- .hour, .minute, .second, .microsecond: hour, minute, second, microsecond
- .tzinfo: time zone information
- .replace([hour[, minute[, second[, microsecond[, tzinfo]]]]]): Create a new time object and replace the attributes in the original object with the hours, minutes, seconds, and microseconds specified by the parameters (the original object remains unchanged);
- .isoformat: The return type is a string representation in the format of “HH:MM:SS”;
- .strftime(fmt): Returns a custom formatted string.
.hour, .minute, .second, .microsecond: hour, minute, second, microsecond
.tzinfo: time zone information
.replace([hour[, minute[, second[, microsecond[, tzinfo]]]]]): Create a new time object and replace the attributes in the original object with the hours, minutes, seconds, and microseconds specified by the parameters (the original object remains unchanged);
.isoformat: The return type is a string representation in the format of “HH:MM:SS”;
.strftime(fmt): Returns a custom formatted string.
Like date, two time objects can also be compared, or subtracted to return a time interval object. No examples are provided here.
datetime class
datetime is a combination of date and time, including all the information of date and time. Its constructor is as follows: datetime.datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]), the meaning of each parameter is the same as that in the constructor of date and time Again, pay attention to the range of parameter values.
Class attributes and methods defined by the datetime class:
- min, max: the minimum and maximum values that datetime can represent;
- resolution: the smallest unit of datetime;
- today: returns a datetime object representing the current local time;
- now([tz]): Returns a datetime object representing the current local time. If the parameter tz is provided, the local time of the time zone pointed to by the tz parameter is obtained;
- utcnow: returns a datetime object of the current utc time;
- fromtimestamp(timestamp[, tz]): Create a datetime object according to the time stamp, and the parameter tz specifies the time zone information;
- utcfromtimestamp(timestamp): Create a datetime object according to the time stamp;
- combine(date, time): Create a datetime object based on date and time;
- strptime(date_string, format): Convert the format string to a datetime object;
min, max: the minimum and maximum values that datetime can represent;
resolution: the smallest unit of datetime;
today: returns a datetime object representing the current local time;
now([tz]): Returns a datetime object representing the current local time. If the parameter tz is provided, the local time of the time zone pointed to by the tz parameter is obtained;
utcnow: returns a datetime object of the current utc time;
fromtimestamp(timestamp[, tz]): Create a datetime object according to the time stamp, and the parameter tz specifies the time zone information;
utcfromtimestamp(timestamp): Create a datetime object according to the time stamp;
combine(date, time): Create a datetime object based on date and time;
strptime(date_string, format): Convert the format string to a datetime object;
importtime
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))
operation result:
datetime.max: 9999-12-3123: 59: 59.999999
datetime.min: 0001-01-0100: 00: 00
datetime.resolution: 0: 00: 00.000001
today: 2016-09-1219: 57: 00.761000
now: 2016-09-1219: 57: 00.761000
utcnow: 2016-09-1211: 57: 00.761000
fromtimestamp(tmstmp): 2016-09-1219: 57: 00.761000
utcfromtimestamp(tmstmp): 2016-09-1211: 57: 00.761000
The instance methods and attributes provided by the datetime class (many attributes or methods have already appeared in date and time, which have similar meanings here. Only these method names are listed here, and the specific meanings will not be introduced one by one. You can refer to the above for date Explanation with the time class.):
year、month、day、hour、minute、second、microsecond、tzinfo:
- date: get the date object;
- time: get the time object;
- replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]]):
- time tuple
- utctimetuple
- toordinal
- weekday
- isocalendar
- isoformat([sep])
- ctime: Returns a C format string of a date and time, equivalent to ctime(time.mktime(dt.timetuple));
- strftime(format)
date: get the date object;
time: get the time object;
replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]]):
time tuple
utctimetuple
toordinal
weekday
isocalendar
isoformat([sep])
ctime: Returns a C format string of a date and time, equivalent to ctime(time.mktime(dt.timetuple));
strftime(format)
Like date, two datetime objects can also be compared, or subtracted to return an interval object, or datetime plus an interval to return a new datetime object.
class timedelta
Returns a timedelta object through the timedelta function, which is an object representing a time interval. The function parameters are as follows:
class datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])
It has no required parameters. If it is simply controlled, the first integer means the interval of how many days:
datetime.timedelta(10)
Two time interval objects can be added or subtracted from each other, and a time interval object is returned. What is more convenient is that if a datetime object is subtracted from a time interval object, then the returned datetime object corresponds to the subtracted datetime object, and then if the two datetime objects are subtracted, the returned time interval object is. This is very convenient.
tzinfo class
tzinfo is an abstract class and cannot be instantiated directly. Subclasses need to be derived to provide the corresponding standard methods. The datetime module does not provide any subclasses of tzinfo. The easiest way is to use the pytz module.
pytz module
Pytz is a time zone processing module for Python (which also includes daylight saving time). Before understanding the time zone processing module, you need to understand some concepts of time zones.
To know the conversion relationship between time zones, it is actually very simple : subtract the local time zone from the local time, and the rest is Greenwich Mean Time. For example, 18:00 in Beijing time is 18:00+08:00, and after subtraction, it is 10:00+00:00, so it is 10:00 in Greenwich Mean Time.
Python’s datetime can handle 2 types of time, offset-naive and offset-aware. The former refers to the time without time zone information, and the latter refers to the time including time zone information. Only the same type of time can be subtracted and compared.
By default, the functions of the datetime module only generate datetime objects of type offset-naive, such as now, utcnow, fromtimestamp, utcfromtimestamp, and strftime. Among them, now and fromtimestamp can accept a tzinfo object to generate a datetime object of offset-aware type, but the standard library does not provide any implemented tzinfo class, and can only implement it by itself.
Here is an example of a tzinfo class that implements GMT and Beijing time:
ZERO_TIME_DELTA = timedelta( 0)
LOCAL_TIME_DELTA = timedelta(hours= 8 ) # local time zone offset
classUTC(tzinfo):
defutcoffset(self, dt):
returnZERO_TIME_DELTA
defdst(self, dt):
returnZERO_TIME_DELTA
classLocalTimezone(tzinfo):
defutcoffset(self, dt):
returnLOCAL_TIME_DELTA
defdst(self, dt):
returnZERO_TIME_DELTA
deftzname(self, dt):
return’+08:00’
A tzinfo class needs to implement the three methods utcoffset, dst and tzname. Among them, utcoffset needs to return the time difference adjustment of daylight saving time; tzname needs to return the time zone name, if you don’t need to use it, you can not implement it.
Once a datetime object of type offset-aware is generated, we can call its astimezone method to generate the time in other time zones (which will be calculated based on the time difference). And if you get a datetime object of offset-naive type, you can also call its replace method to replace tzinfo, but this replacement will not adjust other time attributes according to the time difference. Therefore, if you get a datetime object of offset-naive type of GMT, you can directly call replace(tzinfo=UTC) to convert it to offset-aware type, and then call astimezone to generate datetime objects of other time zones.
Everything seems simple enough, but I don’t know if you remember the daylight saving time mentioned above. Talking about daylight saving time really gives me a headache, because it has no rules to follow: some countries implement daylight saving time, some countries don’t, some countries only implement daylight saving time in some areas, and some areas only implement daylight saving time in certain years. The start and end time of daylight saving time is not necessarily the same in each region, and in some places, TMD does not specify the start and end time of daylight saving time by months and days, but by the number of weeks in a certain month. this form.
The pytz module uses Olson TZ Database to solve the cross-platform time zone calculation consistency problem and solve the calculation problem caused by daylight saving time. Since countries and regions can choose their own time zone and whether to use daylight saving time, the pytz module has to update its own time zone and daylight saving time-related information if necessary.
pytz provides all the timezone information, such as:
importpytz
print(len(pytz.all_timezones))
print(len(pytz.common_timezones))
operation result:
588
436
If you need to get the time zone of a country, you can use the following methods:
importpytz
print(pytz.country_timezones( ‘cn’))
Results of the:
[u’Asia/Shanghai’, u’Asia/Urumqi’]
China has two time zones, one is Shanghai and the other is Urumqi. Let’s see what the difference is:
fromdatetime importdatetime
importpytz
print(pytz.country_timezones( ‘cn’))
tz1 = pytz.timezone(pytz.country_timezones( ‘cn’)[ 0])
print(tz1)
print(datetime.now(tz1))
tz2 = pytz.timezone(pytz.country_timezones( ‘cn’)[ 1])
print(tz2)
print(datetime.now(tz2))
Results of the:
[ u’Asia/Shanghai’ , u’Asia/Urumqi’ ]
Asia/Shanghai
2016-09-1409: 55: 39.384000+ 08: 00
Asia/Urumqi
2016-09-1407: 55: 39.385000+ 06: 00
It can be seen that Shanghai is the East Eighth District, while Urumqi is the East Sixth District.
time zone conversion
The operation is simple and easy, the conversion between the local time zone and UTC:
fromdatetime importdatetime
importpytz
now = datetime.now
tz = pytz.timezone( ‘Asia/Shanghai’)
print(tz.localize(now))
print(pytz.utc.normalize(tz.localize(now)))
Results of the:
2016-09-1410: 25: 44.633000+ 08: 00
2016-09-1402: 25: 44.633000+ 00: 00
Use astimezone to convert between time zones and time zones.
fromdatetime importdatetime
importpytz
utc = pytz.utc
beijing_time = pytz.timezone( ‘Asia/Shanghai’)
japan_time = pytz.timezone( ‘Asia/Tokyo’)
now = datetime.now(beijing_time)
print( “Beijing Time:“,now)
print( “UTC:“,now.astimezone(utc))
print( “JAPAN TIME:“,now.astimezone(japan_time))
Results of the:
Beijing Time: 2016-09-1410: 19: 22.671000+ 08: 00
UTC: 2016-09-1402: 19: 22.671000+ 00: 00
JAPAN TIME: 2016-09-1411: 19: 22.671000+ 09: 00
fromdatetime importdatetime
importpytz
now = datetime.now
print(now)
tz = pytz.timezone( ‘Asia/Shanghai’)
print(now.replace(tzinfo=tz))
Results of the:
2016-09-1410: 29: 20.200000
2016-09-1410: 29: 20.200000+ 08: 06
Daylight Savings Time Handling
Due to the relatively few scenes used, detailed learning is not performed.
dateutil module
Install the module: pip install Python-dateutil
parser.parse
Parse time to datetime format, most time strings are supported. If no time is specified, the default is 0 o’clock, if no date is specified, the default is today, and if no year is specified, the default is this year.
fromdateutil importparser
print(parser.parse( “8th March,2004”))
print(parser.parse( “8 March,2004”))
print(parser.parse( “March 8th,2004”))
print(parser.parse( “March 8,2004”))
print(parser.parse( “2016-09-14”))
print(parser.parse( “20160914”))
print(parser.parse( “2016/09/14”))
print(parser.parse( “09/14/2016”))
print(parser.parse( “09,14”))
print(parser.parse( “12:00:00”))
print(parser.parse( “Wed, Nov 12”))
Results of the:
2004-03-0800: 00: 00
2004-03-0800: 00: 00
2004-03-0800: 00: 00
2004-03-0800: 00: 00
2016-09-1400: 00: 00
2016-09-1400: 00: 00
2016-09-1400: 00: 00
2016-09-1400: 00: 00
2016-09-0900: 00: 00
2016-09-1412: 00: 00
2016-11-1200: 00: 00
rrule.rrule
The main function of the function: generate date and time according to the rules. The function prototype is as follows.
rrule(self, freq, dtstart=None, interval=1, wkst=None, count=None, until=None, bysetpos=None, bymonth=None, bymonthday=None, byyearday=None, byeaster=None, byweekno=None, byweekday=None, byhour=None, byminute=None, bysecond=None, cache=False)
in:
- freq: can be understood as a unit. Can be YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, SECONDLY. That is, the year, month, day, week, hour, minute and second.
- dtstart,until: is the start and end time.
- wkst: Week start time.
- interval: interval.
- count: Specify how many to generate.
- byxxx: Specifies the matching period. For example byweekday=(MO,TU) only matches on Monday and Tuesday. byweekday can specify MO,TU,WE,TH,FR,SA,SU. i.e. Monday to Sunday.
freq: can be understood as a unit. Can be YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, SECONDLY. That is, the year, month, day, week, hour, minute and second.
dtstart,until: is the start and end time.
wkst: Week start time.
interval: interval.
count: Specify how many to generate.
byxxx: Specifies the matching period. For example byweekday=(MO,TU) only matches on Monday and Tuesday. byweekday can specify MO,TU,WE,TH,FR,SA,SU. i.e. Monday to Sunday.
More references: http://dateutil.readthedocs.io/en/stable/index.html
Arrow
Arrow provides a friendly and very understandable method for creating time, calculating time, formatting time, and converting and extracting time, compatible with python datetime type. It includes the dateutil module, which according to its documentation describes Arrow is designed to “help you work with dates and times with less code”.
UTC time
Create UTC time using the utcnow function.
Using the to method, we convert UTC time to local time.
importarrow
utc = arrow.utcnow
print ( utc )
print ( utc . to ( ‘local ’ ))
local time
Local time is the time in a specific region or time zone.
importarrow
now = arrow.now
print(now)
print(now.to( ‘UTC’))
Use the now function to create a local time. The to method is used to convert local time to UTC time.
parsing time
The get method is used to parse the time.
importarrow
d1 = arrow.get( ‘2012-06-05 16:20:03’, ‘YYYY-MM-DD HH:mm:ss’)
print(d1)
d2 = arrow.get( 1504384602)
print(d2)
The example parses time from date and time strings and timestamps.
Unix timestamp import arrow
utc = arrow.utcnow
print ( utc )
unix_time = utc.timestamp
print(unix_time)
date = arrow.Arrow.fromtimestamp(unix_time)
print(date)
The example displays local time and Unix time. Then, it converts the Unix time back to a date object.
Using the fromtimestamp method, we convert the Unix time back to an Arrow date object.
Dates can also be formatted as Unix time.
importarrow
utc = arrow.utcnow
print(utc.format( ‘X’))
By passing the ‘X’ specifier to the format method, we print the current local date as Unix time.
Format date and time
Dates and times can be formatted with the format method.
importarrow
now = arrow.now
year = now.format( ‘YYYY’)
print( “Year: {0}“.format(year))
date = now.format( ‘YYYY-MM-DD’)
print( “Date: {0}“.format(date))
date_time = now.format( ‘YYYY-MM-DD HH:mm:ss’)
print( “Date and time: {0}“.format(date_time))
date_time_zone = now.format( ‘YYYY-MM-DD HH:mm:ss ZZ’)
print( “Date and time and zone: {0}“.format(date_time_zone))
Format description:
Convert to regional time import arrow
utc = arrow.utcnow
print(utc.to( ‘US/Pacific’).format( ‘HH:mm:ss’))
print(utc.to( ‘Europe/Bratislava’).format( ‘HH:mm:ss’))
print(utc.to( ‘Europe/Moscow’).format( ‘HH:mm:ss’))
working day
The weekday of a date can be found using the weekday or format methods.
importarrow
d1 = arrow.get( ‘1948-12-13’)
print(d1.weekday)
print(d1.format( ‘dddd’))
moving time
The shift method is used to shift time.
importarrow
now = arrow.now
print(now.shift(hours= 5).time)
print(now.shift(days= 5).date)
print(now.shift(years= -8).date)
daylight saving time import arrow
now = arrow.now
print(now.format( “YYYY-MM-DD HH:mm:ss ZZ”))
print(now.dst)
The example uses dst to display daylight saving time.
Humanized date and time
On social networking sites, we often see terms like “an hour ago” or “5 minutes ago” that can give people quick information about when a post was created or modified. Arrow includes a humanize method to create such terms.
importarrow
now = arrow.now
d1 = now.shift(minutes= -15).humanize
print(d1)
d2 = now.shift(hours= 5).humanize
print(d2)
ISO 8601 class
The international standard ISO 8601 is the date and time representation method of the International Organization for Standardization.
>>> importdateutil.parser
>>> dateutil.parser.parse( ‘2008-09-03T20:56:35.450686Z’) # RFC 3339 format
datetime.datetime( 2008, 9, 3, 20, 56, 35, 450686, tzinfo=tzutc)
>>> dateutil.parser.parse( ‘2008-09-03T20:56:35.450686’) # ISO 8601 extended format
datetime.datetime( 2008, 9, 3, 20, 56, 35, 450686)
>>> dateutil.parser.parse( ‘20080903T205635.450686’) # ISO 8601 basic format
datetime.datetime( 2008, 9, 3, 20, 56, 35, 450686)
>>> dateutil.parser.parse( ‘20080903’) # ISO 8601 basic format, date only
datetime.datetime( 2008, 9, 3, 0, 0)
Or use the following way to parse:
>>> datetime.datetime.strptime( “2008-09-03T20:56:35.450686Z”, “%Y-%m-%dT%H:%M:%S.%fZ”)
Alternatively you can use the iso8601 module: http://pyiso8601.readthedocs.io/en/latest/
Other date and time tools:
- Gregorian to Lunar: https://pypi.python.org/pypi/LunarSolarConverter/
- Colloquial Date: https://github.com/scrapinghub/dateparser
- Moment : https: //github.com/zachwill/moment
- Delorean:https://github.com/myusuf3/delorean
- When:https://whenpy.readthedocs.io/en/latest/
- Pendulum:https://pendulum.eustace.io/
- Time Machine: https://github.com/spuec/freezegun
- Work Calendar: https://github.com/peopledoc/workalendar
- Chinese statutory holidays: https://github.com/NateScarlet/holiday-cn
Gregorian to Lunar: https://pypi.python.org/pypi/LunarSolarConverter/
Colloquial Date: https://github.com/scrapinghub/dateparser
Moment : https: //github.com/zachwill/moment
Delorean:https://github.com/myusuf3/delorean
When:https://whenpy.readthedocs.io/en/latest/
Pendulum:https://pendulum.eustace.io/
Time Machine: https://github.com/spuec/freezegun
Work Calendar: https://github.com/peopledoc/workalendar
Chinese statutory holidays: https://github.com/NateScarlet/holiday-cn
Thanks for reading this far!
Latest Programming News and Information | GeekBar