I'm writing Python and I'm not a Python person.

I have a need to get a Unix timestamp of a time that is an arbitrary number of days ago.

In PowerShell, you can do something like this:

PS > Get-Date -Date (Get-Date).AddDays(-30) -UFormat %s

In Python, this is the best I came up with and it is ugly:

import re
import datetime

`int(re.split('\\.',str((datetime.datetime.now(datetime.UTC) - datetime.timedelta(days=30)).timestamp()))[0])`

That was from me reading module documentation and hacking away at it for a bit.

Surely, there is a better way.

I'm interfacing with an API that only takes datetime in Unix Time format and only down to the second in precision.

#Python #DateTime #UnixTime #EpochTime

@jrdepriest

Out of my mind, I'd try to use numpy. If I remember well you can use an arbitrary date and set precision.

@jrdepriest

import datetime

unix_time = int((datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(days=30)).timestamp())

That was mine using datetime. Pretty much the same as others.

But using numpy, it is a little bit longer:

import numpy as np

unix_time = int((np.datetime64('now') - np.timedelta64(30, 'D')).astype('datetime64[s]').astype(int))