I have this code, recieve a unix timestamp from a server which is 2 hours ahead of my time. My time is SAST and theirs is GMT +2.
I convert this timestamp in python to a readable datetime like this
import datetime
unixtimestamp = 1507126064
datetime.datetime.fromtimestamp(unixtimestamp).strftime('%Y-%m-%d %H:%M:%S')
The problem is that this time comes back two hours ahead of me, so what would be the easiest way to minus two hours or make it local time.
With datetime.timedelta object:
from datetime import datetime, timedelta
unix_ts = 1507126064
dt = (datetime.fromtimestamp(unix_ts) - timedelta(hours=2)).strftime('%Y-%m-%d %H:%M:%S')
print(dt)
Related
I am trying to convert the local time into UTC time. But getting the below error.
Error: an integer is required (got type str)
from datetime import datetime
starts_date = '2021-07-30 09:30:00'(timestamp without time zone)
ts = starts_date
x = datetime.utcfromtimestamp(ts)
x_ts = x.timestamp()
Be sure that datetime is imported correctly as from datetime import datetime. Can be a bit confusing but the method utcfromtimestamp belongs to datetime.datetime and not datetime itself.
Here is a working example to convert a timestamp of (now) to a UTC timestamp.
from datetime import datetime as dt
# Create a timestamp object for now.
ts = dt.timestamp(dt.now())
# Convert now to a UTC timestamp.
dt.utcfromtimestamp(ts).timestamp()
>>> 1627637013.657752
datetime.utcfromtimestamp() takes an integer that represent the amount of seconds passed since January 1st 1970.
This means with
from datetime import datetime as dt
print(dt.utcfromtimestamp(0))
you get
1970-01-01 00:00:00
What is this date format 2020-01-13T09:25:19-0330 ? and how can I get the current datetime in this format in python ?
Edited: Also note there are only 4 digits after last -. The API which I need to hit accepts exactly this format.
2nd Edit: Confirmed from api's dev team, last 4 digits are milliseconds, with 0 prepended. ex, 330 is the milliseconds, and they mention it as 0330.
It's an ISO 8601 timestamp format.
In order to get the current time in that format:
from datetime import datetime
print(datetime.now().isoformat())
In your case, the iso format is truncated to seconds, and has a timezone:
from datetime import datetime, timezone, timedelta
tz = timezone(timedelta(hours=-3.5))
current_time = datetime.now(tz)
print(current_time.isoformat(timespec="seconds"))
Where -3.5 is the UTC offset.
If you wish to use the system's local timezone, you can do so like this:
from datetime import datetime, timezone, timedelta
current_time = datetime.now().astimezone()
print(current_time.isoformat(timespec="seconds"))
Is there a way to convert time from the year_month_day-hh_mm_ss to timestapm (in milliseconds since 1971) with DateUtils? or some other library..
thanks.
Have a look at the Python datetime and time modules.
from datetime import datetime
d = datetime.strptime("2017_03_16-14:08:10", "%Y_%m_%d-%H:%M:%S")
This will create a datetime object of d
Then use mktime from Python's time module to get your timestamp
import time
time.mktime(d.timetuple())*1000
The *1000 is required to convert from seconds to milliseconds.
Also, do you mean 1971 or the Unix epoch (Jan 01 1970)?
Try the arrow module found at the following URL: https://pypi.python.org/pypi/arrow
You can parse the time with strptime, then you can get the time since epoch time in milliseconds by using strftime to format only seconds. Multiply by 1000 to get milliseconds.
converted_time.strftime("%s") * 1000
You can use timedelta
from datetime import timedelta
year = timedelta(days=(2017-1971)*365)#number of days from 1971 to 2017
mili_sec = (year.total_seconds())*1000#you will get total_seconds just mulitply with 1000 to get milliseconds
OUTPUT
1450656000000.0
OR
You wanted difference from a particular date.Ex from 1971-01-01 to 2017-03-16-14:08:10
from datetime import datetime
new_day = datetime.strptime("2017_03_16-14:08:10", "%Y_%m_%d-%H:%M:%S")
old_day = datetime.strptime("1971_01_01-00:00:00", "%Y_%m_%d-%H:%M:%S")
diff_day_milliseconds = ((new_day - old_day).total_seconds())*1000
OUTPUT
1458137290000.0
I want to convert 2014-08-14 20:01:28.242 into a unix timestamp 245293529385 and subtract this by the current timestamp in order to figure out how many days have past and are ultimately remaining by subtracting this value from 14.
Scenario: user signs up and I want to count down the number of days remaining in their trial.
time.strptime to the rescue! Use the format string %Y-%m-%d %H:%M:%S.%f. For example:
import time
t = '2014-08-14 20:01:28.242'
ts = time.strptime(t, '%Y-%m-%d %H:%M:%S.%f')
timestamp = time.mktime(ts)
Now to convert it to a datetime (from: How do you convert a Python time.struct_time object into a datetime object? ):
from datetime import datetime
dt = datetime.fromtimestamp(timestamp)
There are two parts:
Convert input time string into datetime object
#!/usr/bin/env python
from datetime import datetime
dt = datetime.strptime('2014-08-14 20:01:28.242', '%Y-%m-%d %H:%M:%S.%f')
Convert datetime object to Unix time ("seconds since epoch")
The result depends on what time zone is used for the input time e.g., if the input is in UTC then the corresponding POSIX timestamp is:
timestamp = (dt - datetime(1970,1,1)).total_seconds()
# -> 1408046488.242
If your input is in the local timezone then see How do I convert local time to UTC in Python?
I've been struggling to determine how I can generate a POSIX (UNIX) time value for today and yesterday (midnight) via Python. I created this code, but keep stumbling with how to convert them to a POSIX value:
from datetime import datetime, timedelta
import time
today_string = datetime.now().strftime('%Y-%m-%d 00:00:00')
yesterday_string = (datetime.now() - timedelta(0)).strftime('%Y-%m-%d 00:00:00')
today = datetime.strptime(today_string, '%Y-%m-%d %H:%M:%S')
yesterday = datetime.strptime(yesterday_string, '%Y-%m-%d %H:%M:%S')
print time.mktime(today).timetuple()
This code yields an exception:
TypeError: argument must be 9-item sequence, not datetime.datetime
At this point, I'm at my wits end. Any help you can provide is appreciated.
You should apply the timetuple() method to the today object, not to the result of time.mktime(today):
>>> time.mktime(today.timetuple())
1345845600.0
By the way, I'm wrong or yesterday will be equal to today in your code?
edit:
To obtain the POSIX time for today you can simply do:
time.mktime(datetime.date.today().timetuple())
#Bakuriu is right here. But you are making this overcomplex.
Take a look at this:
from datetime import date, timedelta
import time
today = date.today()
today_unix = time.mktime(today.timetuple())
yesterday = today - timedelta(1)
yesterday_unix = time.mktime(yesterday.timetuple())
Since the date object doesn't hold time, it resets it to the midnight.
You could also replace the last part with:
yesterday_unix = today_unix - 86400
but note that it wouldn't work correctly across daylight saving time switches (i.e. you'll end up with 1 AM or 23 PM).
Getting a unix timestamp from a datetime object as a string and as a float:
datetime.now().strftime('%s')
'1345884732'
time.mktime(datetime.now().timetuple())
1345884732.0