python、numpy、pandas的时间处理

一直对时间处理搞得不太明白,这次自己梳理一下,争取以后更容易上手。

1、python自带的datetime类

1.1 datetime类基本操作

    datetime类是date和time的结合体,包括date与time的所有信息,date和time类中具有的方法和属性,datetime类都具有。

所以在我们日常的工作中,可以仅使用datetime类。该类的构造函数:
datetime.datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])
各参数的含义与date、time构造函数中的一样,但是要注意各参数的取值范围。

1、today函数 返回一个当前本地时间的datetime.datetime类的对象。
2、now([tz]) 不指定时区,返回一个当前本地时间的datetime.datetime类的对象。指定时区,返回指定时区的时间

3、给定一个浮点数作为时间戳timestamp,然后利用fromtimestamp(timestamp[,tz]) 返回指定时区的datetime.datetime类的对象。不指定时区,返回本地时区的datetime类对象

4、Datetime类—year、month、day、hour、minute、second属性,用 datetime.timetuple() to get tuple of all attributes

from datetime import datetime as dt
from datetime import date, time, timezone
d_t = dt(2023,1,2,12,11,12,tzinfo=timezone.utc)#直接定义datetime实例,指定UTC时间
d = dt.today()
dt_now = dt.now()
dt_stamp = dt_now.timestamp()#float型
dt_stamp = 1634623112.222
dt_from_stamp = dt.fromtimestamp(dt_stamp )

#通过datetime.combine将date和time合成datetime,
d = date(2005, 7, 14)
t = time(12, 30, 12, 12345)
d_t = dt.combine(d, t)
tt = d_t.timetuple()
for it in tt:   
    print(it)
'''
#输出结果及解释
2005    # year
7      # month
14      # day
12      # hour
30      # minute
12       # second
3       # weekday (0 = Monday)
195     # number of days since 1st January
-1      # dst - method tzinfo.dst() returned Non,dst是夏令时
'''

1.2 datetime格式化输入输出

datedatetime, and time 类都支持通过 strftime(format) 方法来创建一个格式化的字符串来表示时间。strftime(“时间字符串”,format) 将格式时间字符串转换为datetime对象

反过来, datetime.strptime() 方法能够通过解释格式化的时间字符串创建一个 datetime 类实列。strptime(“时间字符串”,format) 将格式时间字符串转换为datetime对象

datetime.isoformat()输出ISO格式的日期时间“”

from datetime import datetime as dt
dt_str_IOS = '2023-01-01T12:13:08.3334'
dt_input = dt.strptime("21/1/06 16:30:24.100312", "%d/%m/%y %H:%M:%S.%f")

dt_str_ISO = dt_input.isoformat()#以ISO标准时间格式输出
dt_input = dt.strptime(dt_str_ISO, '%Y-%m-%dT%H:%M:%S.%f')#以ISO标准时间格式读入时间

下表给出了两个方法的比较:

strftime

strptime

作用

根据给定的格式,将类转换为时间字符串

根据给定的格式将字符串解释为 datetime类实例

方法类型

实例方法(类实例直接调用执行)

类方法(通过类调用)

Method of

datedatetimetime

datetime

Signature

strftime(format)

strptime(date_string, format)

strftime() and strptime() 格式编码

Directive

指令

含义

示例

注释

%a

Weekday as locale’s abbreviated name.

Sun, Mon, …, Sat (en_US);

So, Mo, …, Sa (de_DE)

(1)

%A

Weekday as locale’s full name.

Sunday, Monday, …, Saturday (en_US);

Sonntag, Montag, …, Samstag (de_DE)

(1)

%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

(9)

%b

Month as locale’s abbreviated name.

Jan, Feb, …, Dec (en_US);

Jan, Feb, …, Dez (de_DE)

(1)

%B

Month as locale’s full name.

January, February, …, December (en_US);

Januar, Februar, …, Dezember (de_DE)

(1)

%m

Month as a zero-padded decimal number.

01, 02, …, 12

(9)

%y

Year without century as a zero-padded decimal number.

00, 01, …, 99

(9)

%Y

Year with century as a decimal number.

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

(2)

%H

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

00, 01, …, 23

(9)

%I

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

01, 02, …, 12

(9)

%p

Locale’s equivalent of either AM or PM.

AM, PM (en_US);

am, pm (de_DE)

(1), (3)

%M

Minute as a zero-padded decimal number.

00, 01, …, 59

(9)

%S

Second as a zero-padded decimal number.

00, 01, …, 59

(4), (9)

%f

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

000000, 000001, …, 999999

(5)

%z

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

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

(6)

%Z

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

(empty), UTC, GMT

(6)

%j

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

001, 002, …, 366

(9)

%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

(7), (9)

%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

(7), (9)

%c

Locale’s appropriate date and time representation.

Tue Aug 16 21:30:00 1988 (en_US);

Di 16 Aug 21:30:00 1988 (de_DE)

(1)

%x

Locale’s appropriate date representation.

08/16/88 (None);

08/16/1988 (en_US);

16.08.1988 (de_DE)

(1)

%X

Locale’s appropriate time representation.

21:30:00 (en_US);

21:30:00 (de_DE)

(1)


1.3 时间戳

1.3.1 基本概念时间戳

        Unix时间戳(Unix timestamp),或称Unix时间(Unix time)、POSIX时间(POSIX time),是一种时间表示方式,定义为从格林威治时间1970年01月01日00时00分00秒起至现在的总秒数。Unix时间戳不仅被使用在Unix系统、类Unix系统中,也在许多其他操作系统中被广泛采用。python的datetime时间戳精确到0.1微秒。

1.3.2  时间戳与datetime的转换

(1)可以用利用datetime.datetime.timestamp()函数从datetime实例得到timestamp。

(2)可以用datetime.datetime.fromtimestamp()函数将时间戳变为datetime实例。

# 获取datetime格式的当前时间
now_dt = dt.now()
#获取datetime时间的posix时间戳(相较于1970-1-1)
now_dtstamp = now_dt.timestamp()

# 将时间格式转换成指定格式的时间字符串
now_dtstr = dt.strftime('%Y%m%d%H%M%S')

#根据指定的时间戳数值,得到datetime时间
timeStamp = 1557502800
sp_dt = dt.fromtimestamp(timeStamp)

1.4 时区

    python中处理时区的模块主要有pytz、dateutil、datetime等,这里主要采用pyzt模块。

(1)想要看所有的时区:pytz.all_timezones和pytz.common_timezones

(2)想要看某个国家的时区用pytz.country_timezones('国家代码'),常用的国家代码如下:美国、中国、德国分别是‘‘US’’、‘‘cn’’、“de”等。这个代码可以通过pycountry模块来查询。

import pytz
print(pytz.all_timezones)
print(pytz.common_timezones)
print(pytz.country_timezones('cn'))
print(pytz.country_timezones('de'))

#查询国家代码
pip install pycountry
import pycountry as pc
pc_code = pc.countries.get(name = 'Zambia').alpha_2 #这里查询的是“赞比亚”

(3)pytz.timezone(‘时区名’):此方法能获取一个tzinfo对象,该对象可在datetime生成时间中以参数的形式放入,即可生成对应时区的时间。

(4)也可以进行时区转换,详见下面代码

# -*- coding: utf-8 -*-
import pytz
import datetime
 
utc = pytz.timezone('UTC')#实例化一个tzinfo对象
now_time = datetime.datetime.now(tz=utc)
print(now_time)
 
shanghai = pytz.timezone('Asia/Shanghai')
shanghai_time = datetime.datetime.now(tz=shanghai)
print(shanghai_time)

1.5 timedelta类计算时差

(1)基本定义

一个timedelta对象表示一个时间长度,两个日期或者时间的差值。
class datetime.timedelta(days=0,seconds=0,microseconds=0,milliseconds=0,minutes=0,hours=0,weeks=0)
所有的参数都是可选的,默认值为0,参数可以是整数或者浮点数,既可以是整数也可以是负数。
虽然说参数可以传递的单位很多,但是python内部实现只存储了days,seconds和microseconds三种单位,所有其他的单位在计算时都会转换成相应的三种单位:
1 millisecond = 1000 microseconds
1 minute = 60 seconds
1 hour = 3600 seconds
1 week = 7 days
(2)典型应用

两个datetime.datetime类型相减或者两个datetime.date类型相减的结果就是datetime.timedelta类型。

datetime.timedelta具有days/seconds等属性;seconds属性是以一天内总秒数为模的。

datetime.timedelta只有一个方法,datetime.timedelta.total_seconds(),timedelta对应的总秒数。

注:这里要注意一点,datetime分为offset-naive和offset-aware。offset-naive表示不区分时区的相对时间,而offset-aware表示带有社区信息的时间。二者不能直接相减,需要通过datetime.replace(tzinfo = None )或datetime.replace(tzinfo = XXX )来完成变换。

delta_time = datetime.timedelta(days=2,seconds=1800,microseconds=333,hours=18,weeks=0.1,minutes=4)
delta_time.seconds
delta_time.total_seconds()
target_time = datetime.datetime.now(tz = beijing) + delta_time#arget_time是offset-aware
time_delta1 = target_time - datetime.datetime.now(tz = beijing)#这里的now得到是offset-aware时间,所以可以正确执行
time_delta2 = target_time.replace(tzinfo = None) - datetime.datetime.now()#这里的now得到是offset-naive时间,所以需要将target_time用replace(tzinfo = None)函数转化成offset-naive
print(target_time)
print(time_delta1)
print(time_delta2)

2、numpy的datetime64和deltadatetime

2.1 基础知识

    在 numpy 中,我们很方便的将字符串转换成时间日期类型 datetime64datetime 已被 python 包含的日期时间库所占用)。datetime64比datetime类支持的时间精度更高。

datatime64是带单位的日期时间类型,其单位如下:

日期单位代码含义时间单位代码含义
Yh小时
Mm分钟
Ws
Dms毫秒
--us微秒
--ns纳秒
--ps皮秒
--fs飞秒
--as阿托秒

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值