Changing time from epoch time to iso format in Python [duplicate] - python

This question already has answers here:
In Python, how do you convert seconds since epoch to a `datetime` object?
(5 answers)
Closed 8 years ago.
I would like to change the time from epoch time to a format readable by Kml extensions (such as iso format of time).
There is plenty of help to change from epoch to formats like YYYYMMDDHHMMSS and other structs using tuples and mktime, but to .iso formation , i haven't been able to find it.

utcfromtimestamp converts seconds since the epoch to the corresponding UTC datetime.datetime.
datetime.datetime objects have a isoformat method which returns the date as a string in ISO 8601 format.
In [6]: import datetime as DT
In [7]: seconds_since_epoch = 0
In [8]: DT.datetime.utcfromtimestamp(seconds_since_epoch)
Out[8]: datetime.datetime(1970, 1, 1, 0, 0)
In [9]: DT.datetime.utcfromtimestamp(seconds_since_epoch).isoformat()
Out[9]: '1970-01-01T00:00:00'

Related

Python: How to convert a long datetime string to required format [duplicate]

This question already has answers here:
How do I parse an ISO 8601-formatted date?
(29 answers)
Closed 4 months ago.
I have this time here : 2017-08-05T05:21:10.6582942Z
And I want to convert it into %Y-%m-%d %H:%M:%S
I can do that using some funky methods such as :
date = "2017-08-05T05:21:10.6582942Z"
new_date = date[:11] + " " + date[12:][:-9]
But is there any way I can do something cleaner with datetime or some libraries made for this specific purpose ?
Using the datetime library with the strptime method (for parsing) and the strftime method (for formatting), this can be accomplished with no splits and limited slicing as:
from datetime import datetime as dt
date = '2017-08-05T05:21:10.6582942Z'
output = dt.strptime(date[:-2], '%Y-%m-%dT%H:%M:%S.%f').strftime('%Y-%m-%d %H:%M:%S')
Output:
'2017-08-05 05:21:10'
Note:
The slice is needed to remove the last two characters from the string date, as the %f (fractional seconds) formatter only accepts six decimal values, and your string contains seven decimal values.
Per the formatting documentation:
%f: Microsecond as a decimal number, zero-padded to 6 digits.
Start with importing datetime:
import datetime as dt
Convert string to datetime object:
date = "2017-08-05T05:21:10.6582942Z"
new_date = dt.datetime.strptime(date[:-2], "%Y-%m-%dT%H:%M:%S.%f") # -2 slice to since %f only accepts 6 digits.
Format datetime object as string:
format_date = dt.datetime.strftime(new_date, "%Y-%m-%d %H:%M:%S") # returns your format
However, looking at your code it feels your date is already formatted and you don't require the last .strftime() usage.

Converting Date and time to UNIX date format [duplicate]

This question already has answers here:
Convert a column of yyyy-mm-dd datetimes to linux time epoch in Python
(3 answers)
Closed 7 months ago.
I have been trying to convert the date and time given in following format "2021/12/04 11:10:00.000" to UNIX time.I have attached the sample of my program I tried. It does provide me the UNIX time but when I checked for the converted UNIX time it didn't gave me the correct UNIX time conversion.
for i in dx['date']:
year= i[0:4]
month = i[5:7]
day = i[8:10]
hr = i[11:13]
minute = i[14:16]
sec = i[17:19]
time = year+','+month+','+day+','+hr+','+minute+','+sec
print("Debug", time)
unixtime = datetime.datetime(int(year),int(month),int(day),int(hr),int(minute),int(sec)).timestamp()
Convert string datetime to datetime obj, and then retrieve timestamp.
from datetime import datetime
t = "2021/12/04 11:10:00.000"
dt = datetime.strptime(t, "%Y/%m/%d %H:%M:%S.%f")
dt.timestamp()
Output:
1638637800.0

Date Time Format Unknown [duplicate]

This question already has answers here:
How to convert integer timestamp into a datetime
(3 answers)
Closed last year.
I am trying to figure out a time format used by someone else. In addition to the date, I have time with an example being the following:
1641859200000
I cant seem to figure out what time or date time format this is. It cannot be HHMMSS, because in this example the second is 85, which is not possible. Any idea what format this is, and how I can convert it using Python to HH:MM:SS ?
Thank you :)
You have a timestamp in seconds from Epoch since January 1, 1970 (midnight UTC/GMT). To convert to a datetime, use:
from datetime import datetime
print(datetime.fromtimestamp(1641859200000 / 1000))
# Output
2022-01-11 01:00:00
Note: you have to divide by 1000 because this timestamp contains milliseconds and Epoch should be in seconds.
This is a Unix-Timestamp.
You can convert in a human-readable format like this:
from datetime import datetime
timestamp = 1641859200000/1000
dt = datetime.fromtimestamp(timestamp)
print(dt)
Edit: didn't check the actual timestamp, whyever, this has to be divided by 1000 as done in the othe answer.
This probably is a unix timestamp https://en.wikipedia.org/wiki/Unix_time. The factor 1000 stems from a millisecond representation I think. Depends on, from where you got this stamp.
You can convert it using:
>>> datetime.datetime.fromtimestamp(1641859200000/1000)
datetime.datetime(2022, 1, 11, 1, 0)
Take a look at dateparser https://dateparser.readthedocs.io/.
It will help you figure out what the date and time is based on the range of input date strings:
pip install dateparser
>>> import dateparser
>>> dateparser.parse('1641859200000')
datetime.datetime(2022, 1, 11, 1, 0)
Your timestamp is miliseconds since Unix epoch in this case but if you ever run into similar problem dateparser could help you.
Regarding the second part of the question. Convertion to HH:MM:SS format
>> dt = datetime.datetime(2022, 1, 11, 1, 0)
>> dt.strftime("%H:%M:%S")
'01:00:00'
Additional info: Available Format Codes

How to convert HH:MM:SS to time.time() object in Python [duplicate]

This question already has answers here:
Convert string "Jun 1 2005 1:33PM" into datetime
(26 answers)
Closed 2 years ago.
I need to convert HH:MM:SS format to time.time() object. Is there any way to do it?
Here's my HH:MM:SS format time:
a = '14:37:29'
I want to convert it to time.time() object such as:
a = 1600256249
Is this achievable? If it's not, what should I try? Hope you help.
To get UNIX time, you need to add a date. For example, you could combine your time string with today's date:
from datetime import datetime, timezone
s = '14:37:29'
today = datetime.today() # 2020-09-16
# make a datetime object with today's date
dt = datetime.combine(today, datetime.strptime(s, '%H:%M:%S').time())
# make sure it's in UTC (optional)
dt = dt.replace(tzinfo=timezone.utc)
# get the timestamp
ts = dt.timestamp()
print(ts)
# 1600267049.0
You could also set other time zones with this approach using dateutil or zoneinfo (Python 3.9+).
Is this achievable?
I would say no. a = '14:37:29' holds only hour-minute-second, whilst time.time() does return seconds since start of epoch i.e. you would also need to known day, month and year beside hour, minute, second, to create equivalent of what time.time() returns.

How to convert current datetime into 13 digits Unix timestamp? [duplicate]

This question already has answers here:
How can I convert a datetime object to milliseconds since epoch (unix time) in Python?
(14 answers)
Closed 3 years ago.
I want to convert current datetime into Unix time stamp
My Code
import time
import datetime
d = datetime.datetime.now()
unixtime = time.mktime(d.timetuple())
print(unixtime)
My output:
1577098747.0
Expected Output:
1577098747123.0
Above code gives me timestamp upto 10 digits but I want it to be accurate till 13 digits.
Note: I don't want to convert it manually multiplying by 10**3 I want to capture accurate milliseconds.
do it like this
import time
import datetime
d = datetime.datetime.now()
unixtime = datetime.datetime.timestamp(d)*1000
print(unixtime)
or you just use time.time()

Categories

Resources