Home > Blockchain >  How to convert a date to Unix epoch time in Python?
How to convert a date to Unix epoch time in Python?

Time:01-19

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!

CodePudding user response:

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)
  • Related