The common operations of the time module are summarized as the following functions:
#! /usr/bin/env python
# - *- coding: utf-8-*-import sys
reload(sys)
sys.setdefaultencoding('utf-8')import time
import datetime
import calendar
def second_to_datetime_string(seconds):"""
Convert the number of seconds starting from AD 0 to the string form of datetime
: param seconds:The number of seconds since AD 0
: return:string form of datetime
"""
s = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(float(seconds)))
year = s.split('-',1)[0]
rest = s.split('-',1)[1]
year =int(year)-1970 #The datetime is from 1970, so you need to subtract 1970return when calculating'{}-{}'.format(str(year), rest)
def gregorian_date_to_str(year, month, day):"""
Convert the AD date into a string, with 4 digits for year, 2 digits for month, 2 digits for day, and 0 if the number of digits is insufficient:param year:Year, e.g. 2017:param month:Month, such as 8 or 08:param day:Day, such as 12 or 02 or 2:return:Returns a string with a fixed number of digits, such as 2017-08-22"""
return'{}-{}-{}'.format(
year,
month iflen(str(month))==2else'0{}'.format(month),
day iflen(str(day))==2else'0{}'.format(day))
def gregorian_date_to_str_1(year, month, day):"""
Convert the AD date into a string, with 4 digits for year, 2 digits for month, 2 digits for day, and 0 if the number of digits is insufficient:param year:Year, e.g. 2017:param month:Month, such as 8 or 08:param day:Day, such as 12 or 02 or 2:return:Returns a string with a fixed number of digits, without-, Such as 20170822"""
return'{}{}{}'.format(
year,
month iflen(str(month))==2else'0{}'.format(month),
day iflen(str(day))==2else'0{}'.format(day))
def get_element_from_date_str(date_str):"""Get the year, month, and day of a date string"""return date_str[0:4], date_str[4:6], date_str[6:8]
def is_valid_date(date_str):"""Determine whether it is a valid date string"""try:
time.strptime(date_str,'%Y%m%d')return True
except ValueError:return False
def get_latter_1_day_str(date_str):"""
Get data_Date string of the day after str
: param date_str:Specify date string
: return:Returns the date string one day after the specified date string
"""
dt = datetime.datetime.strptime(date_str,'%Y%m%d')
one_day = datetime.timedelta(days=1)
former_day = dt + one_day
return former_day.strftime('%Y%m%d')
def get_latter_n_day_str(date_str, n):"""
Get data_Date string n days after str
: param date_str:Specify date string
: return:Returns the date string n days after the specified date string
"""
dt = datetime.datetime.strptime(date_str,'%Y%m%d')
one_day = datetime.timedelta(days=days)
former_day = dt + one_day
return former_day.strftime('%Y%m%d')
def get_yesterday_str():"""
Get yesterday's date string
: return:Returns yesterday's date string
"""
today = datetime.date.today()
one_day = datetime.timedelta(days=1)
yesterday = today - one_day
return yesterday.strftime('%Y%m%d')
def get_former_1_day_str(date_str):"""
Get data_date string of the day before str
: param date_str:Specify date string
: return:Returns the date string of the day before the specified date string
"""
dt = datetime.datetime.strptime(date_str,'%Y%m%d')
one_day = datetime.timedelta(days=1)
former_day = dt - one_day
return former_day.strftime('%Y%m%d')
def get_former_n_day_str(date_str, n):"""
Get data_Date string of n days before str
: param date_str:Specify date string
: param n: number of day
: return:Returns the date string n days before the specified date string
"""
dt = datetime.datetime.strptime(date_str,'%Y%m%d')
n_day = datetime.timedelta(days=n)
former_n_day = dt - n_day
return former_n_day.strftime('%Y%m%d')
def get_universal_time():"""
Get current time
: return:Returns the current time, format: 2017-08-2902:43:19"""
t = time.gmtime()
time_tuple =(t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec)
dt = datetime.datetime(*time_tuple)return dt.strftime('%Y-%m-%d %H:%M:%S')
def datetime_to_gregorian_seconds(dt):"""
Get the number of seconds that have passed since January 1, 0, 0 o'clock on the current day
: param dt: datetime.datetime type
: return:Returns the number of seconds that have elapsed since January 1, 0, 0 o'clock on that day
"""
d = dt.date()
t = dt.time()
# toordinal from January 1, 1,datetime in erlang_to_gregorian_seconds and date_to_gregorian_days start on January 1, 0
# The day is not counted so you need to subtract 1 day
return(d.toordinal()+365-1)*86400+time_to_second(t.hour, t.minute, t.second)
def time_to_second(time_h, time_m, time_s):"""
According to the given time_h, time_m, time_s Calculate the elapsed time of the day, in seconds
: param time_h:hour
: param time_m:Minute
: param time_s:second
: return:Returns the calculated second
"""
returnint(time_h)*3600+int(time_m)*60+int(time_s)
def utc_time_to_second(utc_time):"""
According to the given utc_time calculates the elapsed time of the day, in seconds
: param utc_time:utc timestamp, similar to 1464830584:return:Returns the calculated second
"""
t = datetime.datetime.fromtimestamp(int(utc_time))return t.hour *3600+ t.minute *60+ t.second
def get_today_start_time():"""Get the start time of the day"""
dt = datetime.datetime.combine(datetime.date.today(), datetime.time.min)return dt.strftime('%Y-%m-%d %H:%M:%S')
def get_today_end_time():"""Get the end time of the day"""
dt = datetime.datetime.combine(datetime.date.today(), datetime.time.max)return dt.strftime('%Y-%m-%d %H:%M:%S')
def get_final_day_of_current_week():"""Get the last day of the week: Sunday"""
today = datetime.date.today()
sunday = today + datetime.timedelta(6- today.weekday())return sunday.strftime('%Y-%m-%d')
def get_final_day_of_current_month():"""Get the last day of the month"""
today = datetime.date.today()
_, last_day_num = calendar.monthrange(today.year, today.month)
last_day = datetime.date(today.year, today.month, last_day_num)return last_day.strftime('%Y-%m-%d')
def get_final_day_of_last_month():"""Get the last day of the previous month, may be New Year's Eve, you need to use timedelta"""
today = datetime.date.today()
first = datetime.date(day=1, month=today.month, year=today.year)
final_day_of_last_month = first - datetime.timedelta(days=1)return final_day_of_last_month.strftime('%Y-%m-%d')
def get_final_day_of_current_month(year, month):"""Get the last day of the specified month of the specified year"""
_, last_day_num = calendar.monthrange(year, month)return last_day_num
# last_day = datetime.date(year, month, last_day_num)
# return last_day.strftime('%Y-%m-%d')
Recommended Posts