datetime converting format in python - python-3.x

have list of an other lists that contains date (y,m,d h,m,s,ms), and an other list of some values. I would plot this values in function of date but I couldn't convert the first list on date. How can I do this?
import datetime
import matplotlib
from time import mktime
import datetime as dt
from datetime import datetime
date = [
['"2017/10/27"', '"08:18:12"', ' 0.400'],
['"2017/10/27"', '"08:18:12"', ' 0.500'],
['"2017/10/27"', '"08:18:12"', ' 0.600']
]
values = [2,4,5]
for i in range(len(date)):
date[i][0] = eval(date[i][0])
date[i][1] = eval(date[i][1])
date[i][2] = date[i][2].strip()
date = [' '.join(elem) for elem in date]
>>>['2017/10/27 08:18:12 0.400', '2017/10/27 08:18:12 0.500', '2017/10/27
08:18:12 0.600']
date = [mktime(datetime.strptime(elem,'%Y-%m-%d %H:%M:%S
0.%f').timetuple()) for elem in date]
>>ValueError: time data '2017/10/27 08:18:12 0.400' does not match format
'%Y-%m-%d %H:%M:%S 0.%f
I have lists of thousands of lines so if some could this more efficiently I'll be very grateful. thank you in advance.

Your error message actually tells you exactly what's wrong :) The python function you're using, does pattern matching to find the different elements (minutes, hours, etc) in your time string.
You're using:
date = [mktime(datetime.strptime(elem,'%Y-%m-%d %H:%M:%S 0.%f').timetuple()) for elem in date]
but your time string is '2017/10/27 08:18:12 0.400'. You're using / and not - as a separator, so the function above can't find a matching string. Change your code above to:
date = [mktime(datetime.strptime(elem,'%Y/%m/%d %H:%M:%S 0.%f').timetuple()) for elem in date]

Related

Python datetime conversion

import datetime as dt
from dateutil.tz import gettz
import time
timezone_a = "Japan"
timezone_b = "Europe/London"
unix_time = 1619238722
result = dt.datetime.fromtimestamp(unix_time, gettz(timezone_a)).strftime("%Y-%m-%d-%H-%M-%S")
print(result, timezone_a)
result = dt.datetime.fromtimestamp(unix_time, gettz(timezone_b)).strftime("%Y-%m-%d-%H-%M-%S")
print(result, timezone_b)
# This code prints
"""
2021-04-24-13-32-02 Japan
2021-04-24-05-32-02 Europe/London
I am trying to reverse it backwards so that input is
2021-04-24-13-32-02 Japan
2021-04-24-05-32-02 Europe/London
And output is 1619238722
"""
Hello, I am trying to figure out how to convert a string with a timezone into Unix time. Any help would be apreciated. Thanks!
afaik, there is no built-in method in the standard lib to parse IANA time zone names. But you can do it yourself like
from datetime import datetime
from zoneinfo import ZoneInfo # Python 3.9+
t = ["2021-04-24-13-32-02 Japan", "2021-04-24-05-32-02 Europe/London"]
# split strings into tuples of date/time + time zone
t = [elem.rsplit(' ', 1) for elem in t]
# parse first element of the resulting tuples to datetime
# add time zone (second element from tuple)
# and take unix time
unix_t = [datetime.strptime(elem[0], "%Y-%m-%d-%H-%M-%S")
.replace(tzinfo=ZoneInfo(elem[1]))
.timestamp()
for elem in t]
# unix_t
# [1619238722.0, 1619238722.0]
See if this code works.
# convert string to datetimeformat
date = datetime.datetime.strptime(date, "%Y-%m-%d-%H-%M-%S %Z")
# convert datetime to timestamp
unixtime = datetime.datetime.timestamp(date)

String time convert to only timestamp using python

I have a time 00:11:21.600000 like this in each row of excel I want to convert to time stamp in hrs and mins
Adding onto Juilian Focks answer, if you have a column named df["time"], you can convert each element into timestamp object by iterating over it as :
from datetime import datetime
for i in range(0,len(df["time"])):
df["time"][i] = df["time"][i].strftime("%H:%M")
or you could use list comprehension as :
dt_array = [x.strftime("%H:%M") for x in df["time"]]
then dt_array contains whole column as datetime object
You can use the inbuilt datetime module:
from datetime import datetime
your_time = datetime.strptime('00:11:21.600000', '%H:%M:%S.%f')
Then you have a datetime object your_time on which you can perform different actions, for example:
Get str with hours and minutes: your_time.strftime('%H:%M')
For more methods see the docs here.

Python string to datetime-date

I've got lots of dates that look like this: 16.8.18 (American: 8/16/18) of type string. Now, I need to check if a date is in the past or future but, datetime doesn't support the German format.
How can I accomplish this?
from datetime import datetime
s = "16.8.18"
d = datetime.strptime(s, "%d.%m.%y")
if d > datetime.now():
print('Date is in the future.')
else:
print('Date is in the past.')
Prints (today is 20.7.2018):
Date is in the future.
The format used in strptime() is explained in the manual pages.

Sort by datetime in python3

Looking for help on how to sort a python3 dictonary by a datetime object (as shown below, a value in the dictionary) using the timestamp below.
datetime: "2018-05-08T14:06:54-04:00"
Any help would be appreciated, spent a bit of time on this and know that to create the object I can do:
format = "%Y-%m-%dT%H:%M:%S"
# Make strptime obj from string minus the crap at the end
strpTime = datetime.datetime.strptime(ts[:-6], format)
# Create string of the pieces I want from obj
convertedTime = strpTime.strftime("%B %d %Y, %-I:%m %p")
But I'm unsure how to go about comparing that to the other values where it accounts for both day and time correctly, and cleanly.
Again, any nudges in the right direction would be greatly appreciated!
Thanks ahead of time.
Datetime instances support the usual ordering operators (< etc), so you should order in the datetime domain directly, not with strings.
Use a callable to convert your strings to timezone-aware datetime instances:
from datetime import datetime
def key(s):
fmt = "%Y-%m-%dT%H:%M:%S%z"
s = ''.join(s.rsplit(':', 1)) # remove colon from offset
return datetime.strptime(s, fmt)
This key func can be used to correctly sort values:
>>> data = {'s1': "2018-05-08T14:06:54-04:00", 's2': "2018-05-08T14:05:54-04:00"}
>>> sorted(data.values(), key=key)
['2018-05-08T14:05:54-04:00', '2018-05-08T14:06:54-04:00']
>>> sorted(data.items(), key=lambda item: key(item[1]))
[('s2', '2018-05-08T14:05:54-04:00'), ('s1', '2018-05-08T14:06:54-04:00')]

Inverse of .tm_yday

I'm trying to do the inverse of calculating the yearday of a date (see code below), e.g. I would like to create a date from a integer number which is my 'yearday'.
Finding tm_day of a date:
from datetime import date
d = date(2015,12,1)
yearday = d.timetuple().tm_yday
Finding date of an integer (e.g. 335) and a given year (e.g. 2015):
???
I managed to solve this question with help of Is there an inverse of python's date.timetuple().tm_yday?
from datetime import datetime, timedelta
date_first_jan = date(2015, 1, 1)
date_new = date_first_jan + timedelta(335)

Resources