0

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!

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
  • Unix time stats at Jan 1, 1970. So you need to get the delta time from 1970. See : https://stackoverflow.com/questions/4192971/in-powershell-how-do-i-convert-datetime-to-unix-time?force_isolation=true – jdweng Jan 18 '23 at 11:22
  • why not provide some Python code you tried? – FObersteiner Jan 18 '23 at 11:57
  • see [this answer](https://stackoverflow.com/a/52512015/10197418) on how to parse a date given as a string to a Python datetime object and then convert to Unix time. Note the caveat though; you must set tzinfo to UTC if the input date represents a UTC date instead of local time. – FObersteiner Jan 18 '23 at 12:41

1 Answers1

1
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)
tomasborrella
  • 480
  • 2
  • 8
  • `datetime.datetime.now()` gives local time, so I don't think this code gives a correct result if "age" spans a DST transition. Note: 1) Unix time is relative to a UTC date, it does not know of DST vs. 2) timedelta arithmetic is wall clock time arithmetic, so it *does* include DST (transitions). – FObersteiner Jan 18 '23 at 12:03
  • This indeed gives back today's date and not the date of -5 days. – Stefan Meeuwessen Jan 18 '23 at 17:54
  • Quite weird, I removed the age and entered 5 instead and it worked... odd. – Stefan Meeuwessen Jan 18 '23 at 18:31