# Python 日期格式和时间以及当前时间和时间戳

**URL:** <https://www.isharkfly.com/t/python/13389>\
**Category:** Python\
**Tags:** python\
**Created:** [March 12, 2021, 4:01pm UTC](https://www.isharkfly.com/t/python/13389 "2021-03-12T16:01:29Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![honeymoose](https://www.isharkfly.com/user_avatar/www.isharkfly.com/honeymoose/32/20796_2.png) [@honeymoose](https://www.isharkfly.com/u/honeymoose)\
**Post date:** [March 12, 2021, 4:01pm UTC](https://www.isharkfly.com/t/python/13389/1 "2021-03-12T16:01:29Z")

</div>

Python 程序在运行的时候可能需要获得当前的时间。

在这个时候我们需要导入 datetime 包。

## 获得当前时间

例如，可以使用下面的代码获得当前的日期。

```auto
today = datetime.date.today()
print("Today's date:", today)

```

在上面的代码中，将会输出： Today’s date: 2021-03-12 的内容。

## 格式化日期

当你获得日期对象后，你可以通过 strftime 函数来格式化日子。

```auto
today = datetime.date.today()

print("日期对象格式化输出 1 =", today.strftime("%d/%m/%Y"))
print("日期对象格式化输出 2 =", today.strftime("%B %d, %Y"))
print("日期对象格式化输出 3 =", today.strftime("%m/%d/%y"))
print("日期对象格式化输出 4 =", today.strftime("%b-%d-%Y"))

```

上面的代码将会将会对 date 对象按照输入格式进行格式化。

## 时间戳

可以考虑下下面的代码，下面的代码将会输出日期的时间戳。

```auto
now = datetime.datetime.now()
print("当前时间戳:", now)

```

上面的代码，将会输出为：当前时间戳: 2021-03-12 10:40:02.982640 这样的格式。

![date-now-01](https://www.isharkfly.com/images/transparent.png)

如果你对时间函数还希望有些了解的话，你可以在导入 datetime 包后再进行测试。
