新猿木子李:0基础学python培训教程 Python操作日期

```python

import datetime

# 当前日期和时间

print(datetime.datetime.now())

# 2019-09-30 22:19:37.582514

# 获取指定时间

datetest = datetime.datetime(2019, 9, 30, 22, 22, 0)

print(datetest)

# 2019-09-30 22:22:00

# 获取日期的年月日时分秒

print(str(datetest.year) + "-" + str(datetest.month) + "-" + str(datetest.day) + " " + str(datetest.hour) + ":" + str(

datetest.minute) + ":" + str(datetest.second))

# 2019-9-30 22:22:0

import datetime, time

dt1 = datetime.datetime.fromtimestamp(10000)

dt2 = datetime.datetime.fromtimestamp(time.time())

print(dt1)

print(dt2)

# 1970-01-01 10:46:40

# 2019-09-30 23:28:47.629210

import datetime

# 日期转换

datestr = datetime.datetime.strptime('2019-9-30 22:10:00', '%Y-%m-%d %H:%M:%S')

now = datetime.datetime.now()

print(datestr)

print(now.strftime('%a, %b %d %H:%M'))

print(time.strftime('%Y-%m-%d'))

# 2019-09-30 22:10:00

# Tue, Oct 01 00:02

import datetime

# 日期增加和减少

now = datetime.datetime.now()

print(now)

newdate = now + datetime.timedelta(hours=10)

print(newdate)

newdate = now - datetime.timedelta(days=1)

print(newdate)

# 2019-10-01 00:23:50.152118

# 2019-10-01 10:23:50.152118

# 2019-09-30 00:23:50.152118

```

你可能感兴趣的:(新猿木子李:0基础学python培训教程 Python操作日期)