Questions tagged [python-datetime]

Python's built-in datetime module provides classes for manipulating dates and times in both simple and complex ways.

Filter by
Sorted by
Tagged with
-1 votes
0 answers
20 views

Not Null Constraint Failed in Django DateTime field with auto_now_add=True

I have a model in which there is datetime field. The structure is similar to the below one class ModelName(models.Model): uid = models.CharField(max_length = 50, default="") ...
-3 votes
0 answers
27 views

EOFError on input() for multifunction program [closed]

I am writing a very simple (in my mind it's simple) program to allow the user to choose three functions: one converts Celsius to Fahrenheit, the next Fahrenheit to Celsius, and the next one shows how ...
1 vote
2 answers
36 views

Date time difference in minutes python

I'm new to python and tiring to calculate time difference in minutes. Times are in slightly two different formats. I have tried below to format but did not got it correctly from datetime import ...
-1 votes
0 answers
33 views

raise ValueError("time data %r does not match format %r" %

The following code : with open(LL_File_Name, 'r') as LL: LL_str = LL.read() Last_Load = str(datetime.datetime.strptime(LL_str, '%d-%b-%y %H:%M:%S')) produces this error: raise ValueError("...
0 votes
1 answer
25 views

Excel date format to Python date [duplicate]

My data looks like this Date Price 40179 7.65 10210 6.87 I want to change the Date to a YYYY-MM-DD format. It should look like this: Date Price 2010-01-01 7.65 2010-02-01 6.87
-1 votes
0 answers
40 views

Is there an easier way of plotting time data? [closed]

I'm trying to plot things, like beats per minute versus time. The data has been collected over several days, but I want to see the hourly trends (so to speak), so I'm plotting only the time part. This ...
0 votes
0 answers
26 views

Python Dataframe index isocaldenar() code giving different answers in a span of 2 days

I am in a perfect state of confusion and dilemma. I don't know what is going on. I had raised a question couple of days ago with some sample data and code. I already had a working solution but was ...
  • 3,759
-1 votes
1 answer
40 views

How do I convert a timezone aware string literal into a datetime object in Python

I have a string from a 3rd party log file that I need to convert into a datetime object. The log entry is in the form: ... timestamp=datetime.datetime(2023, 2, 25, 15, 59, 21, 410787, tzinfo=tzlocal())...
  • 77.8k
1 vote
0 answers
27 views

How to parse non-zero paded datetime string with strptime when leading zero is optional? Thanks

I've been trying to parse a datetime string in a file names with datetime.datetime.strptime(). import datetime datetime.datetime.strptime('2023110912', "%Y%m%d%H%M") datetime.datetime....
0 votes
0 answers
13 views

Insert aggregated value for matching dates of two dataframes with different datetime range

I am relatively new to python and hope i'll find help for my problem which I am sitting on for days.. In my original dataframe I have the columns 'num' (object identifier) 'acquisitions' (datetime) ...
-1 votes
0 answers
30 views

PYTHON ValueError("unconverted data remains: %s" % ValueError: unconverted data remains: -01-01

if date_str: date_str_split = str(item["date_from"]).split() if len(date_str_split) == 1: to_be_formatted_date = datetime.strptime(date_str, "%Y") ...
0 votes
1 answer
85 views

'2023-02-07 10:49:00' instead of '2023-02-07 05:49:00'

I am very confused right now. Here is the timestamp 1675766940000. What is the time using this time format %Y-%m-%d %H:%M:%S. On my local machine, the answer is '2023-02-07 05:49:00' and on a docker ...
  • 7
1 vote
1 answer
17 views

pandas to_datetime is rendering some dates as 'floating' dates

pandas is reading hourly data from 2017-2019 from an excel file. I use the function to_datetime on the index which are dates in the format YYYY-MM-DD HH:MM:SS. train = pd.read_excel(path,index_col=0) ...
0 votes
1 answer
51 views

TypeError: cannot convert the series to <class 'int'> when process dataframe

I want to use is_holiday() in chinesecalendar library to judge holidays based on the information in the time column of dataframe (datetime.date is required to be passed). I extract three integers from ...
1 vote
0 answers
30 views

Convert a directory of csv files into a datetime object

I used yahoo finance to download the Russelll 2000 index with the following columns: ['Date', 'Open', 'High', 'Low', 'Close', 'Volume', 'Dividends', 'Stock Splits', 'SMA_50', 'SMA_100', '...
-1 votes
0 answers
41 views

python datetime issue invalid literal for int() with base 10: '['

I have a an issue with datetime. Below is a piece of code I am working on nc = xr.open_dataset(filename) time = nc['TIME'] time_rounded = np.array(time, dtype='datetime64[D]') # Round/re-arrange time ...
1 vote
1 answer
46 views

Dataframe of start and end dates into sum of days in an array of periods

I have a pandas data frame of start and end dates for contracts. I want to work out the number of in force contract days for all periods (e.g. months) covered by the contracts. Example input: ...
  • 13
0 votes
1 answer
30 views

Is there a way to convert an ISO week number to datetime format without year or day data [closed]

I'm trying to change a short string containing an ISO week number like this: "W24" Into a datetime object where the rest of the data are filled with arbitrary values like this: datetime....
1 vote
1 answer
26 views

Django Correct Date / Time not PC date/time

Is there a way to get the exact date/time from the web rather than taking the PC date/time? I am creating a website where the answer is time relevant. But i don't want someone cheating by putting ...
  • 29
2 votes
1 answer
29 views

Filter dataframe for past 4 quarters

I have a DataFrame with start date and end date as a column. Firstly I need create a new column using End Date which consists of yearquarter (2022Q4) which I did using below code: df['Quarter']=pd....
  • 23
0 votes
1 answer
73 views

Is there a way to optimize this date range transformation? Conditional merge in pandas?

I have Sales data like this as a DataFrame, the datatype of the columns is datetime[64] of pandas: Shop ID Special Offer Start Special Offer End A '2022-01-01' '2022-01-03' B '2022-01-09' '2022-01-...
0 votes
1 answer
30 views

Issue with current time in pandas to_datetime

I am trying to get current timestamp using the following code: pd.to_datetime('now') But this is returning me the timestamp value with a delay of 1 hour. Any idea why this might be happening?
  • 223
0 votes
2 answers
48 views

How to Find the number of times "3AM" was crossed since a certain datetime until now without a While loop?

Below you can find my code. I need to find the number of times a certain hour has passed since a given datetime. In my case, the datetime is 3 AM. I need to find the number of times 3 AM was crossed ...
0 votes
2 answers
27 views

parse_dates in all the columns (unspecified number) when using pd.read_csv

I am reading data from a csv file that contains a multilevel index and a number of columns with dates. The number of columns will change over time. How can I parse all of those dates if I don't know ...
  • 143
0 votes
1 answer
14 views

Make changes on date's list as per needed

I have created a list of dates of current week like this: import datetime now = datetime.datetime.now() dates = [(now + datetime.timedelta(days=d)).strftime("%B %d") for d in range(7)] print ...
0 votes
0 answers
8 views

how to stop an infinite loop occurring within for loop and skip to next ranging in for loop?

my code snippet looks something like this: for i in storelist: #main for loop - runs for multiple store if cond: while cond: #muliple looping conditions while cond2: ...
  • 491
2 votes
1 answer
44 views

Change color of a field in a table depending on how much time is left for the user to pay with Django

I am trying to change the color of a field in a table depending on how much time is left for the user to pay, if there are 7 days to pay it should change to yellow and if it is already the date of ...
0 votes
0 answers
29 views

Get Dates of current week from current date in Python

I am trying to get dates from current date i.e. if today is 8th Feb, I need to get dates from 8th Feb till 15th Feb, I am using following logic: import datetime now = datetime.datetime.now() ...
0 votes
2 answers
55 views

How to convert a float date to days and hours

I have a Dataframe ,you can have it ,by runnnig: import pandas as pd from io import StringIO df = """ case_id duration_time other_column 3456 1 random ...
  • 3,332
0 votes
0 answers
53 views

django DateTimeField serializer return datetime into string format

I have a serializer that validates datetime fields. import rest_framework.serializers as serializer from django.conf import settings class ValueNestedSerializer(serializer.Serializer): lower = ...
  • 3,701
0 votes
1 answer
50 views

How to change column dtype from object to Date/Time in pandas

How to chage the datatypes of Data and Time columns from object datatype to Date and Time datatypes respectively? pd_to_datetime doesnot work. df['Time'] = pd.to_datetime(df['Time'], format='%H:%M:%S'...
0 votes
1 answer
59 views

Creating an empty dataframe in pandas with column of type datetime64[ns, Europe/Paris]

I want to create an empty dataframe in pandas with a single column 'time'. I also want it to be of type datetime64[ns, 'Europe/Paris'], ie. to be able to store timezone-aware timestamps. I actually ...
  • 406
0 votes
0 answers
36 views

How to resolve VariantTimeToSystemTime error while reading/converting dates?

def count_messages_in_folder(folder, message_count, sent_dates): for item in folder.Items: message_count += 1 try: sent_date = item.SentOn if sent_date is ...
0 votes
0 answers
15 views

Error at running my script with demand forecast

I'm trying to make a script with demand forecast but my following code is giving this error, do you know how to solve it, please? My code: import pandas as pd from sklearn.linear_model import ...
0 votes
0 answers
31 views

using pytz library, convert a list of utc offsets (e.g. UTC-10:00) to named time zones (e.g. Pacific/Honolulu)

i`m trying to translate this list of utc offsets: ['UTC-12:00','UTC-11:00','UTC-10:00','UTC-09:00','UTC-08:00','UTC-07:00','UTC-06:00','UTC-05:00','UTC-04:00','UTC+10:00','UTC+12:00'] into a list of ...
1 vote
2 answers
88 views

Calculating rate of return for multiple time frames (annualized, quarterly) with daily time series data (S&P 500 (SPX index) daily prices)

I have a CSV file with some 30 years worth of daily close prices for the S&P 500 (SPX) stock market index, and I read it as Dataframe Series with Dates set as Index. Dataframe: Date Open High Low ...
  • 15
1 vote
0 answers
21 views

Is there a way to explicitly parameterise for timezeone aware datetime object via typing hints in a function in python?

I want to deploy a type hint to show whether a datetime object parameter for a function should be timezone aware (or not). Is there a way to do this of the form (or similar): import datetime as dt ...
1 vote
1 answer
62 views

Convert monthly data to weekly data with pandas based on the monthly difference

I am trying to convert monthly data to weekly data, however, I want continously update the weekly value based on the monthly difference, rather than just simply duplicating the value (as displayed ...
  • 67
2 votes
1 answer
28 views

How to join a series of pandas type pandas.Timestamp with another series type datetime.time?

I have a series of pandas.Timestamp pandas with dates in %Y-%m-%d format and another series of datetime.time with hours. I would like to join both series to have a date with its hour. Here a example ...
1 vote
4 answers
256 views

Python Pandas Convert 10 digit datetime to a proper date format

I have an excel file which contains date format in 10 digit. For example, Order Date as 1806825282.731065, Purchase Date as 1806765295 Does anyone know how to convert them to a proper date format such ...
1 vote
1 answer
108 views

How to change date format using datetime from openpyxl? [duplicate]

I would like to create a function that will convert the date from a string variable to a date format for further processing. The problem is that I managed to isolate the fields where there is no entry ...
  • 71
4 votes
0 answers
48 views

Converting seconds to YYYY-MM-DD HH:MM timestamp. Keeps returning OSError: [Errno 22] Invalid argument [duplicate]

I'm struggling to convert a seconds timestamp to a date because I keep receiving these errot messages that I do not fully understand. secs = 1673715600000 I want this to return the corresponding date ...
0 votes
0 answers
14 views

How do I select all rows of a specific date in a dataframe which contains datetime column with multiple times on that date? [duplicate]

I have a data frame with multiple columns including a datetime column called timestamp, which contains date + time. I would like to filter all rows for a specific date, i.e. all times on that date. ...
0 votes
1 answer
76 views

pd.to_datetime() changing datetime format [duplicate]

I have a DataFrame with a str column of dates like 'time': '2018-02-25T08:00:00.000Z' but when applying pd.to_datetime to that column, the output looks like 'time': '2018-02-25 08:00:00+00:00' Why ...
  • 123
0 votes
2 answers
57 views

How do I group by day of week in SQLAlchemy and sum a certain column for each day of week?

I have a created_at column which stores the datetime.datetime object. And I have a column that stores an integer for each day called as collected. What I want is to group this table by day of week (...
  • 13
1 vote
1 answer
50 views

How to get the last date of the current week or quarter in python?

I would like to find a simple way to get the last date of the current week or quarter. To get the last date of the current month I can use the relativdelta function from dateutil: import pandas as pd ...
0 votes
1 answer
53 views

If condition is True run all cells below in a Jupyter Notebook

I am creating a basic ETL script in Jupyter Notebook that refreshes data daily in a Google Sheet. However, sometimes the database is not updated on it's scheduled time due to a failed load, etc. I ...
  • 93
0 votes
1 answer
46 views

Converting Dates in different format in the Row into number of years

I have a data where it has multiple column representing start and end date of task in different formats. all i want is to create a function that can handle multiple date formats and convert them in ...
  • 181
0 votes
1 answer
38 views

How can I work with dates with years smaller than 1 or bigger than 9999 in python?

I am making a Python script that converts real-life dates into dates for a fantasy world. However, I cannot represent years smaller than 1 or bigger than 9999 using the datetime module, and they may ...
0 votes
1 answer
28 views

Dataframe - How to access datetime properties?

I want to acces datetime object properties like .seconds(), .minutes() etc. Datetime values are stored in Dataframe in column DateTime. I need this acces so I can use np.where() on these values like ...

1
2 3 4 5
37