Python日期时间datetime库与dateutil库典型示例与详解(2)--datetime库datetime类常用例子

本文例子用

from datetime import *

关于python的import和名字空间,请参考之前文章:

《Python日期时间datetime库与dateutil库典型示例与详解(1)--datetime库简介&datetime库date类常用例子》

1、获取当前日期时间

Mydatetime = datetime.today()
Mydatetime = datetime.now()
today()和now()方法在不带参数的情况下,结果完全一致,now()可以输入时区,返回不同时区的当前日期时间,时区相关的应用场景涉及datetime库tzinfo和timezone类,本文不涉及;

2、生成一个指定日期时间的datetime对象

(1)生成指定日期时间的datetime对象时7个参数,分别为年、月、日、小时、分、秒、微秒,

Mydatetime = datetime (2023,11,16,12,12,12,0)

(2)年、月、日必须填写,其他如果没填视为0

Mydatetime = datetime (2023,11,16,12)

(3)生成时要注意各时间单位有效性,否则要抛出异常,例如:
Mydatetime = datetime (2023,11,16,12,12,70)抛出异常,秒单位有效值0-59,输入70不会给我们自动进位到分钟

3、获取datetime对象的各时间单位的数值(返回值为int型)

year = Mydatetime.year
month = Mydatetime.month
day = Mydatetime.day

hour = Mydatetime.hour

minute = Mydatetime.minute

second = Mydatetime.second

microsecond = Mydatetime.microsecond

4、修改datetime对象的各时间单位的数值replace( )

方法与上述的修改date对象的各时间单位的数值一样:
Mydatetime.replace(hour=23,minute =1)
# datetime对象的各时间单位可以单独和组合修改

5、datetime对象的weekday( ) /isoweekday( )/ isocalendar( )/fromisocalendar ( )

datetime类也有weekday( ) /isoweekday( )/ isocalendar( )/fromisocalendar ( )方法,用法分date类完全一样。
换句话说,你要用上述方法应用时,不需要先把datetime对象转换为date对象后再操作。

请参考之前文章:

《Python日期时间datetime库与dateutil库典型示例与详解(1)--datetime库简介&datetime库date类常用例子》

6、datetime对象转换为字符串

共有三种方法,假设date对象

Mydatetime = datetime(2023,11,16,12,12,12,999)

 (1)str类型转换

Mydatetime _string1 = str(Mydatetime) #转化为 '2023-11-16 12:12:12.000999

 (2) datetime类的isoformat()

Mydatetime_string2 = Mydatetime.isoformat()

#转化为ISO标准的日期时间字符串'2023-11-16T12:12:12.000999',跟str()方法在日期与时间的分隔符上不同,str()用空格,isoformat()用大写字母T

 (3) datetime类的strftime()

strftime()更加灵活的让我们进行转换:

Mydatetime_string3 = Mydatetime.strftime('%Y/%m/%d %H:%M:%S.%f ')
#转换结果为'2023/11/16 12:12:12.000999’
Mydatetime_string4 = Mydatetime.strftime('%Y/%m/%d %H:%M:%S ')
#我不需要微秒单位,转换结果为'2023/11/16 12:12:12’
Mydatetime_string4 = Mydatetime.strftime('%Y/%m/%d %H:%M')
#时间我只相保留到分钟级别,转换结果为'2023/11/16 12:12’

7、strftime和strptime中各种%指示符列表

Directive

Meaning

Example

%a

Weekday as locale’s abbreviated name.

Sun, Mon, …, Sat;

%A

Weekday as locale’s full name.

Sunday, Monday, …, Saturday (en_US);

%w

Weekday as a decimal number, where 0 is Sunday and 6 is Saturday.

0, 1, …, 6

%d

Day of the month as a zero-padded decimal number.

01, 02, …, 31

%b

Month as locale’s abbreviated name.

Jan, Feb, …, Dec

%B

Month as locale’s full name.

January, February, …, December

%m

Month as a zero-padded decimal number.

01, 02, …, 12

%y

Year without century as a zero-padded decimal number.

00, 01, …, 99

%Y

Year with century as a decimal number.

0001, 0002, …, 2013, 2014, …, 9998, 9999

%H

Hour (24-hour clock) as a zero-padded decimal number.

00, 01, …, 23

%I

Hour (12-hour clock) as a zero-padded decimal number.

01, 02, …, 12

%p

Locale’s equivalent of either AM or PM.

AM, PM

%M

Minute as a zero-padded decimal number.

00, 01, …, 59

%S

Second as a zero-padded decimal number.

00, 01, …, 59

%f

Microsecond as a decimal number, zero-padded to 6 digits.

000000, 000001, …, 999999

%z

UTC offset in the form ±HHMM[SS[.ffffff]] (empty string if the object is naive).

(empty), +0000, -0400, +1030, +063415, -030712.345216

%Z

Time zone name (empty string if the object is naive).

(empty), UTC, GMT

%j

Day of the year as a zero-padded decimal number.

001, 002, …, 366

%U

Week number of the year (Sunday as the first day of the week) as a zero-padded decimal number. All days in a new year preceding the first Sunday are considered to be in week 0.

00, 01, …, 53

%W

Week number of the year (Monday as the first day of the week) as a zero-padded decimal number. All days in a new year preceding the first Monday are considered to be in week 0.

00, 01, …, 53

%c

Locale’s appropriate date and time representation.

Tue Aug 16 21:30:00 1988

%x

Locale’s appropriate date representation.

08/16/88 (None);

08/16/1988

%X

Locale’s appropriate time representation.

21:30:00

%%

A literal '%' character.

%

%G

ISO 8601 year with century representing the year that contains the greater part of the ISO week (%V).

0001, 0002, …, 2013, 2014, …, 9998, 9999

%u

ISO 8601 weekday as a decimal number where 1 is Monday.

1, 2, …, 7

%V

ISO 8601 week as a decimal number with Monday as the first day of the week. Week 01 is the week containing Jan 4.

01, 02, …, 53

%:z

UTC offset in the form ±HH:MM[:SS[.ffffff]] (empty string if the object is naive).

(empty), +00:00, -04:00, +10:30, +06:34:15, -03:07:12.345216

8、用字符串生成一个指定的datetime对象

用字符串生成datetime对象有两个方法:

(1)strptime()

Mydatetime = datetime.strptime("2023-11-16 12:12:12.999", "%Y-%m-%d %H:%M:%S.%f")
特别注意:微秒单位在这里是往后补零,这里生成的是:
datetime.datetime(2023, 11, 16, 12, 12, 12,999000)
要生成999微秒字符串应该是:"2023-11-16 12:12:12.000999"
如果位数不够,后面也会继续补零,"2023-11-16 12:12:12.00099",生成的是:
datetime.datetime(2023, 11, 16, 12, 12, 12,000990)

(2)fromisoformat () python3.7以后版本支持

Mydatetime = datetime.fromisoformat ("2023-11-16 12:12:12")
这里ISO格式的“日期时间”字符串遵循ISO 8601包括很多:最常见的就是"2023-11-16 12:12:12"这种形式,秒后面可以加小数点,例如"2011-11-04 00:05:23.000283",下面是更多的官方例子: 
datetime.fromisoformat('2011-11-04')
datetime.datetime(2011, 11, 4, 0, 0)
datetime.fromisoformat('20111104')
datetime.datetime(2011, 11, 4, 0, 0)
datetime.fromisoformat('2011-11-04T00:05:23')
datetime.datetime(2011, 11, 4, 0, 5, 23)
datetime.fromisoformat('2011-11-04T00:05:23Z')
datetime.datetime(2011, 11, 4, 0, 5, 23, tzinfo=datetime.timezone.utc)
datetime.fromisoformat('20111104T000523')
datetime.datetime(2011, 11, 4, 0, 5, 23)
datetime.fromisoformat('2011-W01-2T00:05:23.283')
datetime.datetime(2011, 1, 4, 0, 5, 23, 283000)
datetime.fromisoformat('2011-11-04 00:05:23.283')
datetime.datetime(2011, 11, 4, 0, 5, 23, 283000)
datetime.fromisoformat('2011-11-04 00:05:23.283+00:00')
datetime.datetime(2011, 11, 4, 0, 5, 23, 283000, tzinfo=datetime.timezone.utc)
datetime.fromisoformat('2011-11-04T00:05:23+04:00')   
datetime.datetime(2011, 11, 4, 0, 5, 23,tzinfo=datetime.timezone(datetime.timedelta(seconds=14400)))

9、datetime与date类型的相互转换

(1)date转datetime对象,其时分秒单位的值是0点0分0秒0微秒,有两种方法:

方法1:strptime:

date1_to_datetime = datetime.strptime(str(date1),'%Y-%m-%d')

方法2:datetime类的combine方法

date1_to_datetime = datetime.combine(date1, time())

这里我们还使用到了datetime库的time类, time()就是生成个0点0分0秒的time对象,date对象和time对象做个combine操作就得到了datetime对象

(2)datetime转date对象

datetime.date()方法就能等到date对象

datetime1_date = datetime1.date()

10、用字符串生成一个指定的date对象

字符串生成一个指定的date对象有两种途径:

(1)用date类的fromisoformat ()python3.7以后版本支持
Mydate = date.fromisoformat ("2023-11-16")
下面是更多的官方例子:
date.fromisoformat("2019-12-04")
datetime.date(2019, 12, 4)
date.fromisoformat(v20191204")
datetime.date(2019, 12, 4)
date.fromisoformat("2021-W01-1")
datetime.date(2021, 1, 4)
(2) strptime()方法
date类并没有strptime()方法,但是strptime()灵活度高,适用场景广,我们可以先生成datetime对象,再用datetime类的date()方法转换为date对象,更多的strptime()使用例子详见:《用字符串生成一个指定的datetime对象》
Mydate = datetime.strptime("2023-11-16", "%Y-%m-%d").date()

11、中文的时间字符串生成一个指定的datetime对象

例如:2001年2月2日21时32分22秒

Mydatetime = datetime.strptime("2001年2月2日21时32分22秒", "%Y年%m月%d日%H时%M分%S秒")
匹配规则的编写,必须要保证所有参与匹配的时间字符串的字符都要匹配上,哪怕是个空格,下面的写法都会报错:
"%Y年%m月%d日%H时%M分%S"
"%Y年%m月%d日 %H时%M分%S秒" 

如果我们遇到计数都是中文的情况,例如:二零二一年九月二十一日,那得先把中文数字转为阿拉伯数字,python 已有现场的cn2an库可以实现中文数字转为阿拉伯数字的互转

pip install cn2an

你可能感兴趣的:(python基础,python,开发语言)