简体   繁体   中英

How to convert a date to Unix epoch time in Python?

I've been working on learning a bit of Python and I was wondering how I can convert today's date -x days to a unix epoch timestamp?

I've done this before with Powershell. However, since I am learning Python right now, I was wondering how I can do the exact same in Python as I've done with this Powershell script down below;

#### Variables ####
$age = 5 # Maximum age of a file

#### Get date and convert to Epoch ####
$epochtime = Get-Date $((Get-Date).AddDays(-$age).ToUniversalTime()) -UFormat +%s

Write-Host $epochtime

So far, from documentation I've read I have only come across examples where a hard date was given and once I've tried adding timedelta(days=-3) it ended up not working... I'm sure it's just a minor thing I am overlooking, however I'm not sure how to convert date to unix epoch timestamp using specifically the timedelta(days=-3 function in Python.

I'd love some feedback!

import datetime

# Variables
age = 5 # Maximum age of a file

# Get date and convert to Epoch
epochtime = int((datetime.datetime.now() - datetime.timedelta(days=age)).timestamp())

print(epochtime)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM