Transform datetime in YYYY-MM-DD HH:MM[:SS[.SSSSSS]]

28,780

If that's literally what you need.

now = datetime.now().strftime("%Y-%m-%d %H:%M[:%S[.%f]]")

More likely, the square brackets indicate optional parts. So:

now = datetime.now().strftime("%Y-%m-%d %H:%M")

or

now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

or

now = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
Share:
28,780
Filipe Ferminiano
Author by

Filipe Ferminiano

Updated on February 16, 2020

Comments

  • Filipe Ferminiano
    Filipe Ferminiano about 4 years

    I'm receiving this error:

    Could not parse 'event_date' as a timestamp. Required format is YYYY-MM-DD HH:MM[:SS[.SSSSSS]]
    

    from BigQuery when I'm trying to insert a row.

    This is my code:

    bigquery_client = bigquery.Client.from_service_account_json(CREDENTIALS_BIGQUERY, 'roas-164016')
    dataset = bigquery_client.dataset(BQ_LOGS_DATASET_NAME)
    table = dataset.table(BQ_EMAIL_SENDS_TABLE_NAME)
    
    data = {}
    now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    data['send_id'] = 'test'
    data['uid'] = 'test'
    data['account_id'] = 'test'
    data['subaccount_id'] = 'test'
    data['event_id'] = 'test'
    data['event_date'] = now
    data['html_content'] = 'test'
    data['campaign_name'] = 'test'
    data['subject'] = 'test'
    data['send_type'] = 'test'
    
    json_data = json.dumps(data)
    
    data =  json.loads(json_data)
    table.reload()
    
    rows = [data]
    errors = table.insert_data(rows)
    

    How can I fix the date formatting?

  • OneCricketeer
    OneCricketeer about 7 years
    If it's optional, then the question already has the right format
  • Mikhail Berlyant
    Mikhail Berlyant about 7 years
    so just curious - what actually was the problem? accepted answer has (looks like) nothing new to compare with question :o) can you please shed light here?