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

@jrdepriest the str/re.split is redundant and a bit silly; you can round off the non-integer part of the timestamp by simply calling int() on it directly if that’s what you’re trying to do

@glyph @jrdepriest yip, pretty much that:

int((datetime.datetime.now(datetime.UTC) - datetime.timedelta(days=30)).timestamp())
@glyph Thanks! Like I said, I'm not a Python person. I just recently started going through some beginner level training. Stripping out the str and re bits does, indeed work. Converting to int works, just like @nyanbinary shows.

@jrdepriest datetimes in python are powerful, but a bit verbose and sometimes messy. But, I think yours can be streamlined a bit.
I may be missing something, but unsure why you need the regex in there?

import datetime

ts = int((datetime.datetime.utcnow() - datetime.timedelta(days=30)).timestamp())

@jrdepriest not sure if it's directly applicable, but I find arrow to be a very helpful library when working with time in python: https://arrow.readthedocs.io/en/latest/
Arrow: Better dates & times for Python β€” Arrow 🏹 1.4.0 documentation