import time
from time import gmtime, strftime
t = time.localtime()print(time.asctime(t))print(strftime("%a, %d %b %Y %H:%M:%S +0000",gmtime()))print(strftime("%A",gmtime()))print(strftime("%D",gmtime()))print(strftime("%B",gmtime()))print(strftime("%y",gmtime()))#Convert seconds into GMT dateprint(strftime("%a, %d %b %Y %H:%M:%S +0000",gmtime(1234567890)))----------------------------------------------
Sun May 709:30:372017
Sun,07 May 201704:00:37+0000
Sunday
05/07/17
May
17
Fri,13 Feb 200923:31:30+0000
将天、小时、分钟转换为秒
SECONDS_PER_MINUTE =60
SECONDS_PER_HOUR =3600
SECONDS_PER_DAY =86400#Read the inputs from user
days =int(input("Enter number of Days: "))
hours =int(input("Enter number of Hours: "))
minutes =int(input("Enter number of Minutes: "))
seconds =int(input("Enter number of Seconds: "))#Calculate the days, hours, minutes and seconds
total_seconds = days * SECONDS_PER_DAY
total_seconds = total_seconds +( hours * SECONDS_PER_HOUR)
total_seconds = total_seconds +( minutes * SECONDS_PER_MINUTE)
total_seconds = total_seconds + seconds
#Display the resultprint("Total number of seconds: ","%d"%(total_seconds))----------------------------------------------
Enter number of Days:5
Enter number of Hours:36
Enter number of Minutes:24
Enter number of Seconds:15
Total number of seconds:563055
使用 Pandas 获取当前日期和时间
import pandas as pd
print(pd.datetime.now())print(pd.datetime.now().date())print(pd.datetime.now().year)print(pd.datetime.now().month)print(pd.datetime.now().day)print(pd.datetime.now().hour)print(pd.datetime.now().minute)print(pd.datetime.now().second)print(pd.datetime.now().microsecond)----------------------------------------------2018-01-1916:08:28.3935532018-01-19201811916828394553
将字符串转换为日期时间对象
from datetime import datetime
from dateutil import parser
d1 ="Jan 7 2015 1:15PM"
d2 ="2015 Jan 7 1:33PM"#If you know date format
date1 = datetime.strptime(d1,'%b %d %Y %I:%M%p')print(type(date1))print(date1)#If you don't know date format
date2 = parser.parse(d2)print(type(date2))print(date2)----------------------------------------------
class 'datetime.datetime'2015-01-0713:15:00
class 'datetime.datetime'2015-01-0713:33:00
以毫秒为单位获取当前时间
import time
milliseconds =int(round(time.time()*1000))print(milliseconds)----------------------------------------------1516364270650
以 MST、EST、UTC、GMT 和 HST 获取当前日期时间
from datetime import datetime
from pytz import timezone
mst =timezone('MST')print("Time in MST:", datetime.now(mst))
est =timezone('EST')print("Time in EST:", datetime.now(est))
utc =timezone('UTC')print("Time in UTC:", datetime.now(utc))
gmt =timezone('GMT')print("Time in GMT:", datetime.now(gmt))
hst =timezone('HST')print("Time in HST:", datetime.now(hst))----------------------------------------------
Time in MST:2017-01-1906:06:14.495605-07:00
Time in EST:2017-01-1908:06:14.496606-05:00
Time in UTC:2017-01-1913:06:14.496606+00:00
Time in GMT:2017-01-1913:06:14.496606+00:00
Time in HST:2017-01-1903:06:14.497606-10:00
从给定的日期当中获取星期几
import datetime
dayofweek = datetime.date(2010,6,16).strftime("%A")print(dayofweek)#weekdayMonday is 0 and Sunday is 6print("weekday():", datetime.date(2010,6,16).weekday())#isoweekday() Monday is 1 and Sunday is 7print("isoweekday()", datetime.date(2010,6,16).isoweekday())
dayofweek = datetime.datetime.today().strftime("%A")print(dayofweek)print("weekday():", datetime.datetime.today().weekday())print("isoweekday()", datetime.datetime.today().isoweekday())----------------------------------------------
Wednesday
weekday():2isoweekday()3
Friday
weekday():4isoweekday()5
import datetime
start = datetime.datetime.strptime("21-06-2020","%d-%m-%Y")
end = datetime.datetime.strptime("05-07-2020","%d-%m-%Y")
date_generated =[start + datetime.timedelta(days=x)for x in range(0,(end - start).days)]for date in date_generated:print(date.strftime("%d-%m-%Y"))----------------------------------------------21-06-202022-06-202023-06-202024-06-202025-06-202026-06-202027-06-202028-06-202029-06-202030-06-202001-07-202002-07-202003-07-202004-07-2020
from datetime import date
from datetime import timedelta
today = date.today()for i in range(7):
d = today -timedelta(days=i)if d.weekday()<5:print(d)----------------------------------------------2021-05-182021-05-172021-05-142021-05-132021-05-12
import calendar
from datetime import datetime
c = calendar.Calendar(firstweekday=calendar.SUNDAY)
monthcal = c.monthdatescalendar(datetime.today().year, datetime.today().month)
try:
tues =[day for week in monthcal for day in week if
day.weekday()== calendar.TUESDAY and day.month == datetime.today().month][0]print(tues)
except IndexError:print('No date found')----------------------------------------------2021-05-04
将整数转换为日期对象
from datetime import datetime
i =1545730073
timestamp = datetime.fromtimestamp(i)print(timestamp)print(type(timestamp))----------------------------------------------2018-12-2514:57:53
当前日期减去 N 天的天数
from datetime import datetime, timedelta
d = datetime.today()-timedelta(days=5)print(d)----------------------------------------------2021-05-1012:59:14.867969
比较两个日期
import datetime
a = datetime.datetime(2020,12,31,23,59,59)
b = datetime.datetime(2020,11,30,23,59,59)print(a < b)print(a > b)----------------------------------------------
False
True
从 datetime 对象中提取年份
import datetime
year = datetime.date.today().year
print(year)----------------------------------------------2021
from datetime import datetime, timedelta
now = datetime.now()for x in range(7):
d = now -timedelta(days=x)print(d.strftime("%Y-%m-%d"))----------------------------------------------2021-05-182021-05-172021-05-162021-05-152021-05-142021-05-132021-05-12
import calendar
c = calendar.Calendar(firstweekday=calendar.SUNDAY)
year =2021
month =5
monthcal = c.monthdatescalendar(year, month)
try:
third_friday =[day for week in monthcal for day in week if
day.weekday()== calendar.FRIDAY and day.month == month][2]print(third_friday)
except IndexError:print('No date found')----------------------------------------------2021-05-21
从 Python 中的周数获取日期
import datetime
from dateutil.relativedelta import relativedelta
week =25
year =2021
date = datetime.date(year,1,1)+relativedelta(weeks=+week)print(date)----------------------------------------------2021-06-25
from datetime import date, timedelta
yesterday = date.today()-timedelta(days=1)print(yesterday.strftime('%m%d%y'))----------------------------------------------051421
从今天的日期获取上周三
from datetime import date
from datetime import timedelta
today = date.today()
offset =(today.weekday()-2)%7
wednesday = today -timedelta(days=offset)print(wednesday)----------------------------------------------2021-05-12
所有可用时区的列表打印
import pytz
for i in pytz.all_timezones:print(i)-----------------------------------
Africa/Abidjan
Africa/Accra
Africa/Addis_Ababa
Africa/Algiers
Africa/Asmara
Africa/Asmera
Africa/Bamako
Africa/Bangui
Africa/Banjul
Africa/Bissau
...
US/Mountain
US/Pacific
US/Samoa
UTC
Universal
W-SU
WET
Zulu
获取指定开始日期和结束日期之间的日期范围
import datetime
start = datetime.datetime.strptime("21-06-2020","%d-%m-%Y")
end = datetime.datetime.strptime("05-07-2020","%d-%m-%Y")
date_generated =[start + datetime.timedelta(days=x)for x in range(0,(end - start).days)]for date in date_generated:print(date.strftime("%d-%m-%Y"))---------------------------------21-06-202022-06-202023-06-202024-06-202025-06-202026-06-202027-06-202028-06-202029-06-202030-06-202001-07-202002-07-202003-07-202004-07-2020
import datetime
d = datetime.datetime.combine(datetime.date(2020,11,14),
datetime.time(10,23,15))print(d)---------------------------------2020-11-1410:23:15
获得每月的第 5 个星期一
import calendar
c = calendar.Calendar(firstweekday=calendar.SUNDAY)
year =2016
month =2
monthcal = c.monthdatescalendar(year, month)
try:
fifth_monday =[day for week in monthcal for day in week if
day.weekday()== calendar.MONDAY and day.month == month][4]print(fifth_monday)
except IndexError:print('No date found')---------------------------------2016-02-29
将日期时间对象转换为日期对象
from datetime import datetime
datetime_obj =datetime(2020,12,15,10,15,45,321474)print(datetime_obj)
date_obj = datetime_obj.date()print(date_obj)---------------------------------2020-12-1510:15:45.3214742020-12-15
获取没有微秒的当前日期时间
from datetime import datetime
print(datetime.now().isoformat(' ','seconds'))---------------------------------2021-05-1512:55:45
将 N 秒数添加到特定日期时间
import datetime
a = datetime.datetime(2020,12,31,23,59,45)
b = a + datetime.timedelta(seconds=30)print(a)print(b)---------------------------------2020-12-3123:59:452021-01-0100:00:15
from datetime import date
date1 =date(2020,12,23)
date2 =date(2021,5,11)
days =abs(date1 - date2).days
print(days // 7)---------------------------------19
from dateutil.rrule import rrule, WEEKLY, MO
from datetime import date
next_monday =rrule(freq=WEEKLY, dtstart=date.today(), byweekday=MO, count=1)[0]print(next_monday)---------------------------------2021-05-1700:00:00
两个日期之间的差异(以天为单位)
from datetime import date
d1 =date(2019,8,18)
d2 =date(2021,12,10)
days_diff = d2 - d1
print(days_diff.days)---------------------------------845
向当前日期添加六个月
from datetime import datetime
from dateutil.relativedelta import *
date = datetime.now()print(date)
date = date +relativedelta(months=+6)print(date)---------------------------------2021-05-1513:48:52.1356122021-11-1513:48:52.135612
将数据时间对象转换为 Unix(时间戳)
import datetime
import time
#Saturday, October 10,201510:10:00 AM
date_obj = datetime.datetime(2015,10,10,10,10)print("Unix Timestamp: ",(time.mktime(date_obj.timetuple())))---------------------------------
Unix Timestamp:1444452000.0
import datetime
start = datetime.datetime.strptime("2016-06-15","%Y-%m-%d")
end = datetime.datetime.strptime("2016-06-30","%Y-%m-%d")
date_array = \
(start + datetime.timedelta(days=x)for x in range(0,(end-start).days))for date_object in date_array:print(date_object.strftime("%Y-%m-%d"))---------------------------------2016-06-152016-06-162016-06-172016-06-182016-06-192016-06-202016-06-212016-06-222016-06-232016-06-242016-06-252016-06-262016-06-272016-06-282016-06-29
import calendar
print("Year:2002 - Month:2")
month_range = calendar.monthrange(2002,2)print("Weekday of first day of the month:", month_range[0])print("Number of days in month:", month_range[1])print()print("Year:2010 - Month:5")
month_range = calendar.monthrange(2010,5)print("Weekday of first day of the month:", month_range[0])print("Number of days in month:", month_range[1])---------------------------------
Year:2002- Month:2
Weekday of first day of the month:4
Number of days in month:28
Year:2010- Month:5
Weekday of first day of the month:5
Number of days in month:31
打印特定年份的所有星期一
from datetime import date, timedelta
year =2018
date_object =date(year,1,1)
date_object +=timedelta(days=1-date_object.isoweekday())while date_object.year == year:print(date_object)
date_object +=timedelta(days=7)---------------------------------2018-01-012018-01-082018-01-152018-01-222018-01-292018-02-052018-02-12...2018-11-122018-11-192018-11-262018-12-032018-12-102018-12-172018-12-242018-12-31
打印特定年份的日历
import calendar
cal_display = calendar.TextCalendar(calendar.MONDAY)#Year:2019#Column width:1#Lines per week:1#Number of spaces between month columns:0#No. of months per column:2print(cal_display.formatyear(2019,1,1,0,2))---------------------------------
##### 略
从月份编号中获取月份名称
import calendar
import datetime
#Month name from numberprint("Month name from number 5:")
month_num =1
month_abre = datetime.date(2015, month_num,1).strftime('%b')
month_name = datetime.date(2015, month_num,1).strftime('%B')print("Short Name:", month_abre)print("Full Name:", month_name)print("\nList of all months from calendar")#Print list of all months from calendarfor month_val in range(1,13):print(calendar.month_abbr[month_val],"-", calendar.month_name[month_val])---------------------------------
Month name from number 5:
Short Name: Jan
Full Name: January
List of all months from calendar
Jan - January
Feb - February
Mar - March
Apr - April
May - May
Jun - June
Jul - July
Aug - August
Sep - September
Oct - October
Nov - November
Dec - December
from datetime import datetime, timedelta
current_date = datetime.now()
current_quarter =round((current_date.month -1)/3+1)
first_date =datetime(current_date.year,3* current_quarter -2,1)
last_date =datetime(current_date.year,3* current_quarter +1,1)\
+timedelta(days=-1)print("First Day of Quarter:", first_date)print("Last Day of Quarter:", last_date)---------------------------------
First Day of Quarter:2018-01-0100:00:00
Last Day of Quarter:2018-03-3100:00:00