GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Can't upload data with "2019-07-08 08:00:00" datetime format to Google Bigquery with pandas · Issue #56 · googleapis/python-bigquery

This repository was archived by the owner on Mar 6, 2026. It is now read-only.
This repository was archived by the owner on Mar 6, 2026. It is now read-only.

Can't upload data with "2019-07-08 08:00:00" datetime format to Google Bigquery with pandas #56

Copy link
Copy link
Closed
#895
Closed
Can't upload data with "2019-07-08 08:00:00" datetime format to Google Bigquery with pandas#56
#895
Copy link
Assignees
jimfulton
Labels
api: bigqueryIssues related to the googleapis/python-bigquery API.externalThis issue is blocked on a bug with the actual product.priority: p2Moderately-important priority. Fix may not be included in next release.type: bugError or flaw in code with unintended results or allowing sub-optimal usage patterns.

Description

@namnguyenbk
namnguyenbk
opened on Mar 9, 2020
Issue body actions

Environment details

I'm using pandas with google-cloud-python

Steps to reproduce

  1. I have a dataframe has datetime format, ex: "2019-07-08 08:00:00" and my schema has created column with DATETIME type.
  2. I tried covert it to use pq.to_datetime()
  3. Then I used load_table_from_dataframe() to insert data.

Code example

my_df = get_sessions()  # this return a dataframe has a column name is created which is datetime[ns] type ex :"2020-01-08 08:00:00"
my_df['created'] = pd.to_datetime(my_df['created'], format='%Y-%m-%d %H:%M:%S').astype('datetime64[ns]')
res = bigquery_client.client.load_table_from_dataframe(my_df, table_id)
res.result()

# exp: my value "2020-01-08 08:00:00" is being changed as INVALID or this value "0013-03-01T03:05:00" or other wrong value @plamut please help

I just updated my problem . Here
Thanks!

Reacted by kolaworld, Vinicius Passos, Murilo Cunha and J-Ar

Activity

Next
  1. namnguyenbk commented on Mar 9, 2020

    @namnguyenbk
    namnguyenbk
    on Mar 9, 2020
    Author
    More actions

    I tried to change DATETIME to TIMESTAMP on schema but It always has UTC at the end of values. How should I fix them? please!

  2. namnguyenbk
    changed the title [-]Can't upload data with "2019-07-08 08:00:00" datetime format to GBQ with pandas[/-] [+]Can't upload data with "2019-07-08 08:00:00" datetime format to Google Bigquery with pandas[/+] on Mar 9, 2020
  3. busunkim96
    transferred this issue fromgoogleapis/google-cloud-pythonon Mar 9, 2020
  4. product-auto-label
    added
    api: bigqueryIssues related to the googleapis/python-bigquery API.
    on Mar 9, 2020
  5. yoshi-automation
    added
    triage meI really want to be triaged.
    on Mar 10, 2020
  6. plamut
    self-assigned this
    on Mar 10, 2020
  7. namnguyenbk commented on Mar 10, 2020

    @namnguyenbk
    namnguyenbk
    on Mar 10, 2020
    Author
    More actions

    Also, I tried to change this column (df['created']) to milliseconds format, it didn't work. Please help me. Is that a bug.

  8. plamut commented on Mar 10, 2020

    @plamut
    plamut
    on Mar 10, 2020
    Contributor
    More actions

    @namnguyenbk Will investigate this shortly.

    In the meantime, would ti be possible to get a minimal reproducible code sample? And the versions of the libraries used? That would make the investigation easier, thanks!

  9. namnguyenbk commented on Mar 10, 2020

    @namnguyenbk
    namnguyenbk
    on Mar 10, 2020
    Author
    More actions

    googleapis/google-cloud-python#9996
    tswast said change DATETIME -> TIMESTAMP to fix this, but I don't think We should do that, TIMESTAMP on Bigquery has a different format with DATETIME and my client doesn't agree with this format, because it is being forced to UTC format while it is not.
    This is a bug and you guys should fix them to support insert DATETIME to Bigquery by load_table_from_dataframe(). I have used insert_rows_by_dataframe() but it is a streaming buffer API,

  10. namnguyenbk commented on Mar 10, 2020

    @namnguyenbk
    namnguyenbk
    on Mar 10, 2020
    Author
    More actions

    @plamut
    thanks for help me, just wait in a minute, I will get back to you soon

    Reacted by Peter Lamut and ghbarseghyan
  11. plamut
    added
    type: questionRequest for information or clarification. Not an issue.
    and removed
    triage meI really want to be triaged.
    on Mar 10, 2020
  12. plamut commented on Mar 10, 2020

    @plamut
    plamut
    on Mar 10, 2020
    Contributor
    More actions

    @tswast Bringing this to your attention.

    You mentioned back then that the backend lacked support for DATETIME when using Parquet uploads. Are there any updates to your backend feature request?

  13. namnguyenbk commented on Mar 10, 2020

    @namnguyenbk
    namnguyenbk
    on Mar 10, 2020
    Author
    More actions
    my_df = get_sessions()  # this return a dataframe has a column name is created which is datetime[ns] type ex :"2020-01-08 08:00:00"
    my_df['created'] = pd.to_datetime(sessions_df['created'], format='%Y-%m-%d %H:%M:%S').astype('datetime64[ns]')
    res = bigquery_client.client.load_table_from_dataframe(my_df, table_id)
    res.result()
    
    ex: my value "2020-01-08 08:00:00" is being changed as INVALID or this value "0013-03-01T03:05:00" @plamut please help
  14. namnguyenbk commented on Mar 10, 2020

    @namnguyenbk
    namnguyenbk
    on Mar 10, 2020
    Author
    More actions

    @plamut I saw @tswast 's PR to fix this is not a correct solution,
    he has changed "datetime64[ns]": "DATETIME" to "datetime64[ns]": "TIMESTAMP". I think this is a wrong solution because TIMESTAMP of Bigquery force datetime to UTC format . so that is incorrect

    Reacted by Tim Sweña (Swast)
  15. 22 remaining items

  16. plamut commented on Aug 24, 2020

    @plamut
    plamut
    on Aug 24, 2020
    Contributor
    More actions

    I'll try to have a look at this again at the end of the week maybe. In the best case removing the hack that we had to add back then would be enough, meaning that we would would only have to (re)add a test covering this specific case.

    Reacted by Peter Pan
  17. plamut commented on Aug 26, 2020

    @plamut
    plamut
    on Aug 26, 2020
    Contributor
    More actions

    @tswast I tried uploading a DATETIME field, but no luck, I"m afraid.

    google.api_core.exceptions.BadRequest: 400 Error while reading data, error message: Invalid datetime value 1578470400000000 for field 'datetime_col' of type 'INT64' (logical type 'TIMESTAMP_MICROS'): generic::out_of_range: Cannot return an invalid datetime value of 1578470400000000 microseconds relative to the Unix epoch. The range of valid datetime values is [0001-01-1 00:00:00, 9999-12-31 23:59:59.999999]
    

    The error message is a bit surprising, as 1578470400000000 epoch microseconds is actually 2020-01-08 08:00:00, which falls in the range of valid values.


    Posting more details below for a sanity check.

    Modified type map to use DATETIME again:

    diff --git google/cloud/bigquery/_pandas_helpers.py google/cloud/bigquery/_pandas_helpers.py
    index 953b7d0..df66e76 100644
    --- google/cloud/bigquery/_pandas_helpers.py
    +++ google/cloud/bigquery/_pandas_helpers.py
    @@ -55,7 +55,7 @@ _PANDAS_DTYPE_TO_BQ = {
         "datetime64[ns, UTC]": "TIMESTAMP",
         # BigQuery does not support uploading DATETIME values from Parquet files.
         # See: https://github.com/googleapis/google-cloud-python/issues/9996
    -    "datetime64[ns]": "TIMESTAMP",
    +    "datetime64[ns]": "DATETIME",
         "float32": "FLOAT",
         "float64": "FLOAT",
         "int8": "INTEGER",
    

    The script used to test the behavior:

    import pandas as pd
    from google.cloud import bigquery
    
    
    PROJECT = "..."
    DATASET = "..."
    TABLE = "..."
    
    
    def main():
        bigquery_client = bigquery.Client()
    
        table_name = f"{PROJECT}.{DATASET}.{TABLE}"
    
        df = pd.DataFrame({
            "float_col": [0.255, 0.55],
            "datetime_col": ["2020-01-08 08:00:00", "2112-07-22 15:56:00"],
        })
        df = df.astype(dtype={"datetime_col": "datetime64[ns]"})
    
        job_config = bigquery.LoadJobConfig(
            schema=[
                bigquery.SchemaField("float_col", "FLOAT"),
                bigquery.SchemaField("datetime_col", "DATETIME"),
            ],
            write_disposition=bigquery.WriteDisposition.WRITE_TRUNCATE,
        )
        query_job = bigquery_client.load_table_from_dataframe(
            df, table_name, job_config=job_config
        )
        query_job.result()
    
    
    if __name__ == "__main__":
        main()

    The relevant package versions were up to date:

    pandas==1.1.1
    pyarrow==1.0.1
    fastparquet==0.4.1
    

    The parquet file generated and uploaded in the process:
    aaa.parquet.gz

  18. tswast commented on Aug 26, 2020

    @tswast
    tswast
    on Aug 26, 2020
    Contributor
    More actions

    Thanks. I've re-opened the internal bug 147108331. I can replicate this error with the bq command as well

    $ bq load --source_format=PARQUET swast-scratch:my_dataset.aaa ./aaa.parquet ./aaa.schema
    Upload complete.
    Waiting on bqjob_rcdae8f70e185b28_000001742b104318_1 ... (5s) Current status: DONE
    BigQuery error in load operation: Error processing job 'swast-scratch:bqjob_rcdae8f70e185b28_000001742b104318_1': Error while
    reading data, error message: Invalid datetime value 1578470400000000 for field 'datetime_col' of type 'INT64' (logical type
    'TIMESTAMP_MICROS'): generic::out_of_range: Cannot return an invalid datetime value of 1578470400000000 microseconds relative to
    the Unix epoch. The range of valid datetime values is [0001-01-1 00:00:00, 9999-12-31 23:59:59.999999]
    Failure details:
    - prod-scotty-183204df-1614-4661-92c4-727e36ddf960: Error while
    reading data, error message: Invalid datetime value
    1578470400000000 for field 'datetime_col' of type 'INT64' (logical
    type 'TIMESTAMP_MICROS'): generic::out_of_range: Cannot return an
    invalid datetime value of 1578470400000000 microseconds relative to
    the Unix epoch. The range of valid datetime values is [0001-01-1
    00:00:00, 9999-12-31 23:59:59.999999]
    

    aaa.schema.zip

  19. tswast commented on Aug 26, 2020

    @tswast
    tswast
    on Aug 26, 2020
    Contributor
    More actions

    Can we confirm that this is converting to microseconds in the Parquet file? Nanoseconds for DATETIME are not supported and eng thinks that may be the cause.

  20. tswast commented on Aug 26, 2020

    @tswast
    tswast
    on Aug 26, 2020
    Contributor
    More actions

    Sorry, I misunderstood the engineers in internal bug 147108331. It was marked fixed because BigQuery no longer loads nonsense DATETIME values when such a file is encountered. Now it raises a validation error.

    I've filed 166476249 as a feature request to properly add support for DATETIME values.

  21. jgadbois commented on Sep 15, 2020

    @jgadbois
    jgadbois
    on Sep 15, 2020
    More actions

    Given the above, what is the recommended way to insert a datetime from pandas into a bigquery DATETIME column?

  22. tswast commented on Sep 15, 2020

    @tswast
    tswast
    on Sep 15, 2020
    Contributor
    More actions

    @jgadbois I suggest the following two workarounds:

    1. Create the table ahead of time, and append to it using the streaming API client.insert_rows_from_dataframe
    2. Use pandas-gbq, which currently serializes to CSV, not Parquet. https://pandas-gbq.readthedocs.io/en/latest/writing.html
    Reacted by John Gadbois
    Reacted by J-Ar
  23. plamut
    removed their assignment
    on Oct 1, 2020
  24. tswast commented on Dec 22, 2020

    @tswast
    tswast
    on Dec 22, 2020
    Contributor
    More actions

    This library recently added the ability to serialize a DataFrame to CSV for upload. With that format, DATETIME columns are supported.

    job_config = bigquery.LoadJobConfig(
        schema=table_schema, source_format=SourceFormat.CSV
    )
    load_job = bigquery_client.load_table_from_dataframe(
        dataframe, table_id, job_config=job_config
    )
    
    Reacted by Nguyen Danh Nam and VinceCabs
  25. VinceCabs commented on May 19, 2021

    @VinceCabs
    VinceCabs
    on May 19, 2021
    More actions

    that was a great workaround, thanks!

  26. Lingesh7 commented on Jun 22, 2021

    @Lingesh7
    Lingesh7
    on Jun 22, 2021
    More actions

    @tswast your workaround works.

  27. tswast commented on Jun 30, 2021

    @tswast
    tswast
    on Jun 30, 2021
    Contributor
    More actions

    Backend bug with Parquet DATETIME loading (147108331) is reported to be fix in the development server. We should be able remove our client-side workarounds once it rolls out to production.

    Reacted by Anh Tu
  28. tswast
    assigned
    jimfulton
    on Aug 23, 2021
  29. tswast commented on Aug 23, 2021

    @tswast
    tswast
    on Aug 23, 2021
    Contributor
    More actions

    @jimfulton Could you add system tests to https://github.com/googleapis/python-bigquery/blob/master/tests/system/test_pandas.py for uploading DATETIME columns?

    While you're at it, could you add similar tests for TIME columns? I believe this will let us close https://issuetracker.google.com/169230812

    In both cases, there can be a difference between millisecond-precision values and microsecond-precision values, so we should test for both.

    Re: #56 (comment), let's revert the change to the default dtype mapping in a PR to the v3 branch, since that could be considered a breaking change.

    Reacted by Jim Fulton
  30. jimfulton
    closed this as completedin #895on Aug 24, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

  • @jimfulton
    jimfulton

Labels

api: bigqueryIssues related to the googleapis/python-bigquery API.externalThis issue is blocked on a bug with the actual product.priority: p2Moderately-important priority. Fix may not be included in next release.type: bugError or flaw in code with unintended results or allowing sub-optimal usage patterns.

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

    You are visitor 01402775 — GeezerVison does not store the pages you look up.
    Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.