Python’s time processing module is used more often in everyday use, but when using it, you basically have to look up the information, which is still a bit of a hassle, so comb through it to make it easier to use in the future.

Second At the 13th International Conference on Weights and Measures in 1967, it was decided to use the second, defined in atomic time, as the international standard unit of time: the duration of the 9,192,631,770 cycles of radiation corresponding to the leap between the two hyperfine energy levels of the cesium 133 atomic ground state, with the starting calendar element set at 0:00 on January 1, 1958.

An atomic clock is a clock that calculates and maintains accurate time using the atomic resonance frequency standard. The atomic clock is the most accurate time measurement and frequency standard known in the world.

GMT Greenwich Mean Time (GMT), is the standard time at the Royal Greenwich Observatory on the outskirts of London, as the prime meridian is defined as the line of longitude passing through there. GMT is also called Universal Time UT.

UTC Coordinated Universal Time (UTC), also known as Universal Standard Time, is based on the international atomic clock and has an error of a few nanoseconds per day. The second length of Coordinated Universal Time is the same as the second length of Atomic Time, and it is required to be as close as possible to UTC in terms of time (the difference between the two is kept within 0.9 seconds).

Leap seconds There are not only leap years, but also leap seconds. A leap second is an adjustment that adds or subtracts one second from Coordinated Universal Time at the end of the year or in the middle of the year (and possibly at the end of the quarter), as uniformly prescribed by the International Bureau of Weights and Measures, in order to keep Coordinated Universal Time close to the Universal Time moment. Due to the unevenness of the Earth’s rotation and long-term chronicity (mainly caused by tidal friction), it will make the difference between UTC (civil time) and atomic time exceed to ±0.9 seconds, then UTC will be set forward by 1 second (negative leap second, 59 seconds in the last minute) or backward by 1 second (positive leap second, 61 seconds in the last minute); leap seconds are usually added at the end of the Gregorian year or the end of June of the Gregorian calendar.

Time Zones are regions of the Earth that use the same definition of time. The relevant international conferences decided to divide the Earth’s surface into 24 time zones, from south to north, according to longitude lines, and to define the time difference between adjacent zones as 1 hour. When people cross a region, they correct their clocks by one hour (subtract one hour to the west and add one hour to the east), and add or subtract a few hours when they cross several regions. For example, if my country is in the eastern eight zone, it is expressed as GMT+8.

Daylight Saving Time (DST), also known as Daylight Saving Time, Daylight Saving Time or Summer Time. This is a system to save energy and artificially set the local time, in the summer time, the day time will be longer, so in order to save electricity, so in the summer time certain areas will set their time one hour earlier, that is, the original time zone is 8 o’clock well, but because the sun appears earlier in the summer, so move the time forward, in the original 8 o’clock, set as 9 o’clock of that day ( Time one hour earlier) ~ so that we can use the sun to illuminate, save the time spent on electricity, which is why it is called summer time savings!

Unix timestamp refers to the total number of seconds from 0:0:0 UTC on January 1, 1970 to the present, regardless of leap seconds.

Python time module

In the Python documentation, time is categorized under Generic Operating System Services, in other words, it provides functionality that is closer to the operating system level. As you can see from reading through the documentation, the time module is based around the Unix timestamp.

The module mainly consists of a class struct_time, several other functions and related constants. It is important to note that most of the functions in this module call the C library of the platform where they are located, so it is important to note that some functions are platform specific and may have different effects on different platforms. Another point is that, since it is based on Unix Timestamp, the date range is limited to 1970 - 2038, so if you write code that needs to handle dates outside the range described above, you may want to consider using the datetime module.

Get the current time and convert it to time format

  • time() returns the time in timestamp format (offset in seconds relative to 1.1 00:00:00)
  • ctime() returns the time in string form, you can pass in the time stamp format time, used for conversion
  • asctime() returns the time in string form, you can pass in the struct_time form time, used for conversion
  • localtime() returns the current time in struct_time form, can be passed in timestamp format and used to do the conversion
  • gmtime() returns the current time in struct_time form, UTC time zone (0 time zone), can be passed in timestamp format time, used to do the conversion
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
>>> import time
>>> 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 following respectively

  • tm_wday the first day of the week (Sunday is 0)
  • tm_yday The first day of the year
  • tm_isdst whether it is daylight saving time

Time formatting

time.mktime()

Convert a timestamp in struct_time format

1
2
>>> time.mktime(time.localtime())
1473388585.0

time.strftime(format[,t]) Converts a struct_time time into a formatted time string. If t is not specified, it will be passed to time.localtime(). If any element of the tuple is out of bounds, a ValueError error will be thrown.

  • %c local corresponding date and time representation
  • %x local corresponding date
  • %X local corresponding time
  • %y The year with the century removed (00 - 99)
  • %Y Complete year
  • %m month (01 - 12)
  • %b Local simplified month name
  • %B Local full month name
  • %d The first day of a month (01 - 31)
  • %j Number of days in a year (001 - 366)
  • %U Number of days of the week in a year. (00 - 53 Sundays are the beginning of a week.) All days before the first Sunday are placed in week 0.
  • %W is basically the same as %U, except that %W starts a week with Monday.
  • %w The first few days of a week (0 - 6, 0 being Sunday)
  • %a Local (locale) simplified week name
  • %A local complete week name
  • %H The hour of the day (24-hour system, 00 - 23)
  • %I The first few hours (12-hour system, 01 - 12)
  • %p Local am or pm equivalent, “%p” only works in combination with “%I”.
  • %M number of minutes (00 - 59)
  • %S seconds (01 - 61), the documentation emphasizes that it is indeed 0 - 61, not 59, leap year seconds account for two seconds
  • %Z Name of the time zone (null character if not present)
  • %% ‘%’ character
1
2
>>> time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
'2016-09-09 10:54:21'

time.strptime(string[,format])

Converts a formatted time string to struct_time. it is actually the inverse of strftime().

1
2
>>> 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 amount of time. The unit is seconds.

time.clock()

Note that this means different things on different systems. On UNIX systems, it returns the “process time”, which is a floating point number (timestamp) expressed in seconds. In WINDOWS, the first call returns the actual time the process was running. The call after the second time is the running time from the first call to the present. (actually based on QueryPerformanceCounter() on WIN32, which is more accurate than millisecond representation)

1
2
3
4
5
6
7
import time
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 results of the run are.

1
2
3
clock1:1.57895443216e-06
clock2:1.00064381867
clock3:2.00158724394

where the first clock() output is the program run time, the second and third clock() output is the time interval with the first clock

Other built-in functions of the time module

  • altzone() returns the number of seconds offset for the daylight saving time region west of Greenwich. If the region is east of Greenwich it will return a negative value (e.g. Western Europe, including the UK). Only available for daylight saving time enabled regions.
  • tzset() reinitializes time-related settings based on the environment variable TZ.

The time module contains the attributes

  • timezone is the local time zone (without daylight saving time) offset in seconds from Greenwich (>0, Americas; <=0 most of Europe, Asia, Africa).
  • tzname contains a pair of strings that differ depending on the case, the name of the local time zone with daylight saving time and without.
1
2
3
4
5
6
import time

print(time.timezone)
print(time.tzname)
print(time.tzname[0].decode("GBK"))
print(time.tzname[1].decode("GBK"))

Running results

1
2
3
4
-28800
('\xd6\xd0\xb9\xfa\xb1\xea\xd7\xbc\xca\xb1\xbc\xe4', '\xd6\xd0\xb9\xfa\xcf\xc4\xc1\xee\xca\xb1')
中国标准时间
中国夏令时

datetime module

datetime is much more advanced than time, which can be understood as datetime is wrapped based on time and provides more useful functions.

The datetime module defines the following classes.

  • date: A class that represents a date. Commonly used properties are year, month, day
  • time: A class that represents time. Common properties are hour, minute, second, microsecond
  • datetime: the date and time.
  • timedelta: represents the time interval, i.e. the length between two points in time
  • tzinfo: information related to the time zone

Note: All of these types of objects are immutable.

date class

The date class defines some common class methods and class properties:

  • max, min: the maximum and minimum dates that the date object can represent
  • resolution: the smallest unit in which the date object can represent the date. Here is the day
  • today(): returns a date object that represents the current local date
  • fromtimestamp(timestamp): return a date object based on the given time kill
  • fromordinal(ordinal): converts Gregorian calendar time to a date object (not used for special calendars)
1
2
3
4
5
6
7
8
from datetime import date
import time

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()))

Implementation results.

1
2
3
4
5
date.max: 9999-12-31
date.min: 0001-01-01
date.resolution: 1 day, 0:00:00
date.today(): 2016-09-12
date.fromtimestamp(): 2016-09-12

The instance methods and properties provided by date.

  • .year: returns the year
  • .month: returns the month
  • .day: return the day
  • .replace(year, month, day): Generate a new date object, replacing the properties of 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’s Monday, return 1; if it’s week 2, return 2, and so on
  • .isocalendar(): return format like (year, wk num, wk day)
  • .isoformat(): returns a string in format like ‘YYYY-MM-DD’
  • .strftime(fmt): custom formatted string. Similar to strftime in the time module.
  • .toordinal(): return the Gregorian Calendar date corresponding to the date
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from datetime import 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())

Implementation results.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
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 overloads certain operations which allow us to do some of the following with dates.

  • date2 = date1 + timedelta # date plus an interval, returning a new date object
  • date2 = date1 - timedelta # date minus an interval, returning a new date object
  • timedelta = date1 - date2 # two dates subtracted, return an interval object
  • date1 < date2 # Two dates are compared

time class

The constructor for the time class is as follows: (where the parameter tzinfo, which represents the time zone information.)

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

Class properties 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 minimum unit of time, here is 1 microsecond

The time class provides instance methods and properties.

  • .hour, .minute, .second, .microsecond: hour, minute, second, microsecond
  • .tzinfo: time zone information
  • .replace([hour[, minute[, second[, microsecond[, tzinfo]]]]]): creates a new time object, replacing the attributes in the original object with the hours, minutes, seconds, microseconds specified by the parameters (the original object remains unchanged).
  • .isoformat(): return a string representation of the format “HH:MM:SS”.
  • .strftime(fmt): returns a custom formatted string.

Like date, two time objects can be compared or subtracted to return a time interval object. No example will be provided here.

datetime class

datetime is the combination of date and time, including all information of date and time. Its constructor is as follows: datetime.datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]), the meaning of the parameters is the same as in the constructor of date and time, pay attention to the range of parameter values.

The datetime class defines the following class properties and methods.

  • min, max: the minimum and maximum values that datetime can represent.
  • resolution: the minimum unit of datetime.
  • today(): returns a datetime object that represents the current local time.
  • now([tz]): returns a datetime object that represents the current local time, and if the parameter tz is provided, gets the local time in the time zone referred to by the tz parameter; * utcnow(): returns a datetime object that represents the current local time.
  • utcnow(): returns a datetime object representing the current utc time.
  • fromtimestamp(timestamp[, tz]): creates a datetime object based on the time kill, with the parameter tz specifying the time zone information.
  • utcfromtimestamp(timestamp): creates a datetime object based on the time kill.
  • combine(date, time): creates a datetime object based on date and time.
  • strptime(date_string, format): converts a format string to a datetime object.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
from datetime import datetime
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()))

Running results.

1
2
3
4
5
6
7
8
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-09-12 19:57:00.761000
now(): 2016-09-12 19:57:00.761000
utcnow(): 2016-09-12 11:57:00.761000
fromtimestamp(tmstmp): 2016-09-12 19:57:00.761000
utcfromtimestamp(tmstmp): 2016-09-12 11:57:00.761000

datetime class provides examples of methods and properties (many properties or methods have appeared in date and time, here have a similar meaning, here only list the names of these methods, the specific meaning will not be introduced one by one, you can refer to the above explanation of the date and time class. (For more details, please refer to the above explanation of date and time)

year, month, day, hour, minute, second, microsecond, tzinfo.

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

Like date, it is possible to compare two datetime objects, either by subtracting them to return a time interval object, or by adding an interval to the datetime to return a new datetime object.

timedelta class

The timedelta function returns a timedelta object, which is an object that represents a time interval. The parameters of the function are shown below:

class datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])

There are no required parameters, but the first integer is the number of days in the interval if it is a simple control:

datetime.timedelta(10)

Two time interval objects can be added or subtracted from each other and still return a time interval object. And more convenient is a datetime object if you subtract a time interval object, then the return corresponds to the subtracted datetime object, and then two datetime objects if you subtract the return is a time interval object. This is very convenient.

tzinfo class

tzinfo is an abstract class and cannot be instantiated directly. It requires derived subclasses that provide the corresponding standard methods. 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 (also includes daylight saving time). Before understanding the time zone processing module, you need to understand some time zone concepts.

To know the conversion relationship between time zones, it is actually very simple: subtract the local time from the local time zone, and what is left is Greenwich Mean Time. For example, 18:00 Beijing time is 18:00 + 08:00, and after subtracting that, it’s 10:00 + 00:00, so it’s 10:00 Greenwich Mean Time.

Python’s datetime can handle two types of time, offset-naive and offset-aware, the former being times that do not contain time zone information, and the latter being times that contain time zone information, and only times of the same type can be subtracted and compared.

The functions of the datetime module generate only offset-naive type datetime objects by default, such as now(), utcnow(), fromtimestamp(), utcfromtimestamp() and strftime(). Among them, now() and fromtimestamp() can accept a tzinfo object to generate a datetime object of type offset-aware, but the standard library does not provide any implemented tzinfo class, you have to implement it yourself.

The following is an example of a tzinfo class that implements Greenwich Mean Time and Beijing Time.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
ZERO_TIME_DELTA = timedelta(0)
LOCAL_TIME_DELTA = timedelta(hours=8) # 本地时区偏差

class UTC(tzinfo):
    def utcoffset(self, dt):
        return ZERO_TIME_DELTA

    def dst(self, dt):
        return ZERO_TIME_DELTA

class LocalTimezone(tzinfo):
    def utcoffset(self, dt):
        return LOCAL_TIME_DELTA

    def dst(self, dt):
        return ZERO_TIME_DELTA

    def tzname(self, dt):
        return '+08:00'

A tzinfo class needs to implement the 3 methods utcoffset, dst and tzname. Of these, utcoffset needs to return the time difference adjustment for summer time; tzname needs to return the time zone name, or not if you don’t need to use 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 we get a datetime object of type offset-naive, we can also call its replace() method to replace tzinfo, but this replacement will not adjust other time properties according to the time difference. So, if you get a datetime object of offset-naive type with Greenwich Mean Time, you can call replace(tzinfo=UTC()) directly to convert it to offset-aware type, and then call astimezone() to generate datetime objects of other time zones.

It all looks very simple, but I don’t know if you still remember the summer time zone mentioned above. When it comes to summer time, it really gives me a headache because there are no rules to follow: some countries have summer time, some countries don’t, some countries only have summer time in some areas, some areas only have summer time in some years, the start and end of summer time in each area are not necessarily the same, and some places don’t use the fucking days of the month to specify the start and end of summer time, but use In some places, TMD does not specify the start and end of summer season in terms of days of the month, but in terms of days of the week.

The pytz module, using the Olson TZ Database, solves the problem of consistency of time zone calculation across platforms, and solves the calculation problems caused by daylight saving time. Since countries and regions can choose their own time zones and whether or not to use daylight saving time, the pytz module can update its own time zone and daylight saving time related information if needed.

pytz provides full timezone information, such as

1
2
3
4
import pytz

print(len(pytz.all_timezones))
print(len(pytz.common_timezones))

Running results.

1
2
588
436

If you need to get the time zone of a country, you can use the following.

1
2
import pytz
print(pytz.country_timezones('cn'))

Implementation results.

1
[u'Asia/Shanghai', u'Asia/Urumqi']

China one has two time zones, one for Shanghai and one for Urumqi, let’s see what we have the difference between.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
from datetime import datetime
import pytz

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))

Implementation results.

1
2
3
4
5
[u'Asia/Shanghai', u'Asia/Urumqi']
Asia/Shanghai
2016-09-14 09:55:39.384000+08:00
Asia/Urumqi
2016-09-14 07:55:39.385000+06:00

You can see that Shanghai is the eighth eastern district, while Urumqi is the sixth eastern district.

Time zone conversion

The operation has but a relatively simple interchange of local time zone and UTC.

1
2
3
4
5
6
7
from datetime import datetime
import pytz

now = datetime.now()
tz = pytz.timezone('Asia/Shanghai')
print(tz.localize(now))
print(pytz.utc.normalize(tz.localize(now)))

Implementation results.

1
2
2016-09-14 10:25:44.633000+08:00
2016-09-14 02:25:44.633000+00:00

Time zone to time zone conversion is possible using astimezone().

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
from datetime import datetime
import pytz

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))

Implementation results.

1
2
3
Beijing Time: 2016-09-14 10:19:22.671000+08:00
UTC: 2016-09-14 02:19:22.671000+00:00
JAPAN TIME: 2016-09-14 11:19:22.671000+09:00

Alternatively you can use replace to modify the time zone with an extra 6 minutes (do not use). The specific reasons are.

17 years of the Republic of China (1928), the Nationalist government unified China, the former Central Observatory’s business by the Nanjing government Central Research Institute of Astronomy and Meteorological Research Institute received respectively. Astronomical Research Institute compiled the calendar basically follow the practice of the Central Observatory, the country is still divided into five standard time zones, only in relation to the intersection of gas, the conjunction of the first day, the sun’s time, etc., no longer use the local equinox in Beiping, but to Nanjing is located in the standard time zone of the regional time that is 120 ° East longitude standard time instead. There is a difference of 352 seconds between the local equinox of Beiping and 120°E Standard Time.

1
2
3
4
5
6
from datetime import datetime
import pytz
now = datetime.now()
print(now)
tz = pytz.timezone('Asia/Shanghai')
print(now.replace(tzinfo=tz))

Implementation results.

1
2
2016-09-14 10:29:20.200000
2016-09-14 10:29:20.200000+08:06

Daylight saving time processing

Due to the relatively small number of scenarios used, no detailed study is done.

dateutil module

Install the module: pip install python-dateutil

parser.parse()

Parse time to datetime format, support most time strings. The default is 0:00 if no time is specified, today if no date is specified, and this year if no year is specified.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from dateutil import parser

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"))

Implementation results.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
2004-03-08 00:00:00
2004-03-08 00:00:00
2004-03-08 00:00:00
2004-03-08 00:00:00
2016-09-14 00:00:00
2016-09-14 00:00:00
2016-09-14 00:00:00
2016-09-14 00:00:00
2016-09-09 00:00:00
2016-09-14 12:00:00
2016-11-12 00:00:00

rrule.rrule()

Main 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)

where.

  • freq: can be interpreted as units. It can be YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, SECONDLY, i.e. year, month, week, hour, minute and second.
  • dtstart,until: is the start and end time.
  • wkst:Week start time.
  • interval:interval.
  • count:Specifies how many to generate.
  • byxxx:Specify the matching period. For example, byweekday=(MO,TU) then only Monday-Tuesday matches. byweekday can specify MO,TU,WE,TH,FR,SA,SU. i.e. Monday to Sunday.

For more reference: http://dateutil.readthedocs.io/en/stable/index.html

Arrow

Arrow provides a friendly and very easy to understand method for creating times, calculating times, formatting times, and doing conversions, extractions, and compatibility with python datetime types. It includes the dateutil module, and according to its documentation Arrow is designed “to help you handle dates and times with less code”.

UTC time

Use the utcnow() function to create the UTC time.

Using the to() method, we convert the UTC time to local time.

1
2
3
4
5
import arrow

utc = arrow.utcnow()
print(utc)
print(utc.to('local'))

Local time

Local time is the time in a specific region or time zone.

1
2
3
4
5
import arrow

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 the local time to UTC time.

Parsing time

The get() method is used to parse the time.

1
2
3
4
5
6
7
import arrow

d1 = arrow.get('2012-06-05 16:20:03', 'YYYY-MM-DD HH:mm:ss')
print(d1)

d2 = arrow.get(1504384602)
print(d2)

This example parses time from date and time strings and timestamps.

Unix timestamps

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import arrow

utc = arrow.utcnow()
print(utc)

unix_time = utc.timestamp
print(unix_time)

date = arrow.Arrow.fromtimestamp(unix_time)
print(date)

This example displays the local time and the Unix time. It then converts the Unix time back to the date object.

Using the fromtimestamp() method, we convert the Unix time back to the Arrow date object.

You can also format the date to Unix time.

1
2
3
4
import arrow

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.

Formatting the date and time

The date and time can be formatted with the format() method.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import arrow

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

1
2
3
4
5
6
7
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 days

The weekday() or format() method can be used to find the weekday of the date.

1
2
3
4
5
6
import arrow

d1 = arrow.get('1948-12-13')

print(d1.weekday())
print(d1.format('dddd'))

Move time

The shift() method is used to move the time.

1
2
3
4
5
6
7
8
import arrow

now = arrow.now()

print(now.shift(hours=5).time())
print(now.shift(days=5).date())

print(now.shift(years=-8).date())

Daylight Saving Time

1
2
3
4
5
6
import arrow

now = arrow.now()

print(now.format("YYYY-MM-DD HH:mm:ss ZZ"))
print(now.dst())

This example uses dst() to display daylight saving time.

Humanized date and time

On social networking sites, we often see terms such as “one hour ago” or “5 minutes ago” that provide quick information about when a post was created or modified. Arrow includes the humanize() method to create such terms.

1
2
3
4
5
6
7
8
9
import arrow

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, which is the International Organization for Standardization’s representation of date and time, is called “Data storage and exchange forms - Information exchange - Representation of date and time”, and is more involved in API interface development.

1
2
3
4
5
6
7
8
9
>>> import dateutil.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 parsing.

1
>>> datetime.datetime.strptime("2008-09-03T20:56:35.450686Z", "%Y-%m-%dT%H:%M:%S.%fZ")

Also use the iso8601 module: http://pyiso8601.readthedocs.io/en/latest/

Other date and time tools.